带有case语句的SQL Server数据透视表

时间:2014-06-02 09:11:22

标签: sql-server pivot-table

我创建了一个PIVOT表,它在平均结果时工作正常:

)AS PivotTable PIVOT( AVG( Score )FOR KPIID IN( [153],[2],[25],[48] ))AS PivotedTable

但是,我们有一个表格,指定每个项目的分组类型,所以我需要这样的东西:

)AS PivotTable PIVOT( CASE KPIDirection WHEN 1 THEN AVG( Score ) WHEN 2 THEN SUM(Score) END FOR KPIID IN( [153],[2],[25],[48] ))AS PivotedTable

但是这会导致语法错误:

  

关键字' CASE'附近的语法不正确。

有什么想法吗?

[更新] - 完整查询:

SELECT *
  FROM( 
        SELECT ISNULL( Users_KPIs_Daily.UserScore , 0 )AS Score , 
               u.UserID AS UserID , 
               KPIs.KPIID AS KPIID
          FROM KPIs
               LEFT OUTER JOIN Users_KPIs ON KPIs.KPIID = Users_KPIs.KPIID
               LEFT OUTER JOIN Users AS u ON u.UserID = Users_KPIs.UserID
               LEFT OUTER JOIN Users_KPIs_Daily ON Users_KPIs_Daily.UserID = Users_KPIs.UserID
                                               AND Users_KPIs.KPIID = Users_KPIs_Daily.KPIID )AS PivotTable1 

PIVOT( AVG( Score )FOR KPIID IN( [153] , [2] , [25] ,[48] ))AS PivotedTable1

2 个答案:

答案 0 :(得分:3)

好吧,我通过在主表中移动分组找到了解决此问题的方法。所以PIVOT表中的AVG(Score)实际上没有做任何事情,因为记录已经在主表内分组了。 我希望这有助于某人:

SELECT *
  FROM( 
        SELECT CASE DailyKPIGrouping
               WHEN 1 THEN ISNULL( ROUND( AVG( Users_KPIs_Daily.UserScore ) , 2 ) , 0 )
               WHEN 2 THEN ISNULL( SUM( Users_KPIs_Daily.UserScore ) , 0 )
                   ELSE ROUND( SUM( ISNULL( Users_KPIs_Daily.UserScore , 0 ) * ISNULL( Users_KPIs_Daily.CustomData1 , 0 )) / CASE SUM( ISNULL( Users_KPIs_Daily.CustomData1 , 0 ))
                                                                                                                             WHEN 0 THEN 1
                                                                                                                                 ELSE SUM( ISNULL( Users_KPIs_Daily.CustomData1 , 0 ))
                                                                                                                             END , 2 )
               END AS Score , 
               u.UserID AS UserID , 
               KPIs.KPIID AS KPIID
          FROM KPIs JOIN Users_KPIs ON KPIs.KPIID = Users_KPIs.KPIID
                    JOIN Users AS u ON u.UserID = Users_KPIs.UserID
                    LEFT OUTER JOIN Users_KPIs_Daily ON Users_KPIs_Daily.UserID = Users_KPIs.UserID
                                                    AND Users_KPIs.KPIID = Users_KPIs_Daily.KPIID
          GROUP BY KPIs.KPIID , 
                   u.UserID , 
                   DailyKPIGrouping )AS PivotTable1 
PIVOT( AVG( Score )FOR KPIID IN(153] ,[2] , [25] , [41] , [44] ))AS PivotedTable1

答案 1 :(得分:-1)

)AS PivotTable PIVOT( CASE WHEN KPIDirection = 1 THEN AVG( Score )
                       WHEN KPIDirection = 2 THEN SUM(Score) END 
                FOR KPIID IN( [153],[2],[25],[48] )

)AS PivotedTable

请用旧的替换以上行... 然后,问题仍然存在然后显示一点代码..