如何在三个表中使用MAX和Case函数?

时间:2016-02-25 05:03:27

标签: asp.net sql-server

我使用Max和Case函数连接了三个表。

当我使用两个表时它工作正常但是当我添加第三个表时我得到了这个错误。

不明确的列名'月'。

SELECT  Category ,
        KPI ,
        TDTargetValue ,
        MAX(CASE WHEN Month = 'Jan' THEN Input
            END) Jan ,
        MAX(CASE WHEN Month = 'Feb' THEN Input
            END) Feb ,
        MAX(CASE WHEN Month = 'Mar' THEN Input
            END) Mar ,
        MAX(CASE WHEN Month = 'Apr' THEN Input
            END) Apr ,
        MAX(CASE WHEN Month = 'May' THEN Input
            END) May ,
        MAX(CASE WHEN Month = 'Jun' THEN Input
            END) Jun ,
        MAX(CASE WHEN Month = 'Jul' THEN Input
            END) Jul ,
        MAX(CASE WHEN Month = 'Aug' THEN Input
            END) Aug ,
        MAX(CASE WHEN Month = 'Sep' THEN Input
            END) Sep ,
        MAX(CASE WHEN Month = 'Oct' THEN Input
            END) Oct ,
        MAX(CASE WHEN Month = 'Nov' THEN Input
            END) Nov ,
        MAX(CASE WHEN Month = 'Dec' THEN Input
            END) Dec
FROM    [NEWSEMAKPI].[dbo].[NewCriteria] NC
        INNER JOIN ( SELECT *
                     FROM   [NEWSEMAKPI].[dbo].[UpdateData]
                     WHERE  PeriodId = '1'
                   ) UD ON UD.Cid = NC.Id
        LEFT JOIN ( SELECT  *
                    FROM    [NEWSEMAKPI].[dbo].[TargetData]
                  ) TD ON UD.Cid = TD.CId
WHERE   NC.Grade = 'A'
        AND IsActived = '0'
GROUP BY Category ,
        KPI ,
        TDTargetValue
ORDER BY 1

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

也为列Month ...

添加alias

假设NewCriteria表格中有Month

SELECT  Category ,
        KPI ,
        TDTargetValue ,
        MAX(CASE WHEN NC.Month = 'Jan' THEN Input
            END) Jan ,
        MAX(CASE WHEN NC.Month = 'Feb' THEN Input
            END) Feb ,
        MAX(CASE WHEN NC.Month = 'Mar' THEN Input
            END) Mar ,
        MAX(CASE WHEN NC.Month = 'Apr' THEN Input
            END) Apr ,
        MAX(CASE WHEN NC.Month = 'May' THEN Input
            END) May ,
        MAX(CASE WHEN NC.Month = 'Jun' THEN Input
            END) Jun ,
        MAX(CASE WHEN NC.Month = 'Jul' THEN Input
            END) Jul ,
        MAX(CASE WHEN NC.Month = 'Aug' THEN Input
            END) Aug ,
        MAX(CASE WHEN NC.Month = 'Sep' THEN Input
            END) Sep ,
        MAX(CASE WHEN NC.Month = 'Oct' THEN Input
            END) Oct ,
        MAX(CASE WHEN NC.Month = 'Nov' THEN Input
            END) Nov ,
        MAX(CASE WHEN NC.Month = 'Dec' THEN Input
            END) Dec
FROM    [NEWSEMAKPI].[dbo].[NewCriteria] NC
        INNER JOIN ( SELECT *
                     FROM   [NEWSEMAKPI].[dbo].[UpdateData]
                     WHERE  PeriodId = '1'
                   ) UD ON UD.Cid = NC.Id
        LEFT JOIN ( SELECT  *
                    FROM    [NEWSEMAKPI].[dbo].[TargetData]
                  ) TD ON UD.Cid = TD.CId
WHERE   NC.Grade = 'A'
        AND IsActived = '0'
GROUP BY Category ,
        KPI ,
        TDTargetValue
ORDER BY 1