垂直总计按组Pivot SQL

时间:2017-11-17 11:15:35

标签: sql-server tsql pivot totals

我有一个Pivot查询,每个月按群组计算员工登录的次数,我希望每个组获得一个总计,每月在该组员工列表中横向显示。

目前我只能将总数显示为每组的总数作为额外列

我正在使用的SQL是:

   SELECT
   Code,
   Full_Name,
   [1] AS Jan,
   [2] AS Feb,
   [3] AS Mar,
   [4] AS Apr,
   [5] AS May,
   [6] AS Jun,
   [7] AS Jul,
   [8] AS Aug,
   [9] AS Sep,
   [10] AS Oct,
   [11] AS Nov,
   [12] AS Dec,
   Total
   FROM 
   (SELECT Norgren_Group.Code
   , Full_Name
   , lh.Employee_Id
   , MONTH(lh.RN_Create_Date) [Month]
   , COUNT(lh.Employee_Id) OVER (PARTITION BY Norgren_Group_Id) as Total
   FROM Employee_Login_History lh
   JOIN Employee ON Employee.Employee_Id = lh.Employee_Id
   JOIN Norgren_Group ON Norgren_Group.Norgren_Group_Id = Employee.Default_Norgren_Group_Id
   WHERE Reporting_Region='Europe'
   AND YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
   ) pvt
   PIVOT
   (
      COUNT(Employee_Id)
      FOR [Month]
      IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
   ) AS pvttble
   ORDER BY Code, Full_Name

我得到的结果片段是:

 Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0   2894
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0   2894
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0   16899
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0   16899

我想看到的是:

 Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0   
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0   
        Total                33     23  35  17  31  24  26  25  26  43  17  0
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0   
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0   
        Total                17     18  28  9   13  17  18  19  17  22  18  0

1 个答案:

答案 0 :(得分:1)

一种方法是切换到条件聚合并使用GROUPING SETS

SELECT ng.Code, Full_Name,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 1 THEN 1 ELSE 0 END) as Jan,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 2 THEN 1 ELSE 0 END) as Feb,
       . . .
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 12 THEN 1 ELSE 0 END) as Dec
FROM Employee_Login_History lh JOIN
     Employee e
     ON e.Employee_Id = lh.Employee_Id JOIN
     Norgren_Group ng
     ON ng.Norgren_Group_Id = e.Default_Norgren_Group_Id
WHERE Reporting_Region = 'Europe'AND
      YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
GROUP BY GROUPING SETS ( (ng.Code, Full_Name), () );