将总计列添加到动态 SQL 数据透视表

Add Total column to Dynamic SQL pivot

很多这类问题,但找不到任何符合我要找的问题。

我正在使用来自另一个 post 的代码,它运行良好,但我想修改它以在 table.

底部添加一个总计行

之前的post所以创作者获得的荣誉是:

我目前的 table 看起来像:

Work_Group Avg 01/01/2021 01/01/2021 01/01/2021 ect...
Blue 5 2 5 8
Green 5 2 5 8

目标:

Work_Group Avg 01/01/2021 01/01/2021 01/01/2021 ect...
Blue 5 2 5 8
Green 5 2 5 8
TOTAL 10 4 10 16

当前代码是:

DECLARE @colsEAST AS NVARCHAR(MAX);
DECLARE @pivotCountEAST AS NVARCHAR(MAX);
DECLARE @sqlEAST AS NVARCHAR(MAX);

SELECT @colsEAST = ISNULL(@colsEAST + ', ', '') + QUOTENAME(Load_Date)
FROM (SELECT DISTINCT Load_Date FROM ##CE_tmpEast_ALL) AS Load_Date

SET @pivotCountEAST = N'SELECT Work_Group, ' + @colsEAST +'
FROM (SELECT Work_Group, Load_Date, Count FROM ##CEtmp_East_ALL) AS Count
PIVOT(SUM(Count) FOR Load_Date IN (' + @colsEAST + ')) AS pvt';

SET @sqlEAST = '; WITH MTD_CountPivot AS (
'+@pivotCountEAST+'
),

MTD_Pivot_Tables AS (
  SELECT Work_Group, AVG(Count) AS [AVG Count]
  FROM ##CEtmp_East_ALL
  GROUP BY Work_Group
)
SELECT MTD_CountPivot.Work_Group,  MTD_Pivot_Tables.[AVG Count], ' + @colsEAST + '
FROM
MTD_CountPivot

INNER JOIN MTD_Pivot_Tables ON MTD_CountPivot.Work_Group = MTD_Pivot_Tables.Work_Group';

EXEC sp_executesql @sqlEAST;

任何帮助将不胜感激!!!

谢谢

您可以将 GROUPING SETS ((mcp.Work_Group),()) 添加到当前查询以获得小计。为此,需要创建另一个参数 @colsEAST2 以便将生成的列 headers 的日期列表保存为

SUM([2001-01-01]) AS [2001-01-01],SUM([2001-01-02]) AS [2001-01-02],SUM([2001-01-03]) AS [2001-01-03]

@colsEAST 一起持有

[2001-01-01],[2001-01-02],[2001-01-03]

DECLARE @colsEAST       AS NVARCHAR(MAX);
DECLARE @colsEAST2      AS NVARCHAR(MAX);
DECLARE @pivotCountEAST AS NVARCHAR(MAX);
DECLARE @sqlEAST        AS NVARCHAR(MAX);

SELECT @colsEAST = ISNULL(@colsEAST + ', ', '') + QUOTENAME(Load_Date)
  FROM (SELECT DISTINCT Load_Date 
          FROM ##CE_tmpEast_ALL) AS Load_Date;    
SELECT @colsEAST2 = ISNULL(@colsEAST2 + ', ', '') 
                + ' SUM('+QUOTENAME(Load_Date)+') AS '+QUOTENAME(Load_Date)
  FROM (SELECT DISTINCT Load_Date 
          FROM ##CE_tmpEast_ALL) AS Load_Date;    
SET @pivotCountEAST = N'SELECT Work_Group, ' + @colsEAST2 +'
                          FROM (SELECT Work_Group, Load_Date, Count 
                                  FROM ##CE_tmpEast_ALL) AS Count
                         PIVOT(SUM(Count) FOR Load_Date IN (' + @colsEAST + ')) AS pvt
                         GROUP BY Work_Group';                             
SET @sqlEAST = '; WITH MTD_CountPivot AS (
'+@pivotCountEAST+'
), MTD_Pivot_Tables AS (
  SELECT Work_Group, AVG(Count) AS [AVG Count]
    FROM ##CE_tmpEast_ALL
   GROUP BY Work_Group
)
SELECT CASE WHEN GROUPING(mcp.Work_Group) = 0 
            THEN mcp.Work_Group 
            ELSE ''TOTAL'' 
             END AS Work_Group,
       SUM(mpt.[AVG Count]) AS Avg, 
       ' + @colsEAST2+ '
  FROM MTD_CountPivot mcp
  JOIN MTD_Pivot_Tables mpt 
    ON mcp.Work_Group = mpt.Work_Group
 GROUP BY GROUPING SETS ((mcp.Work_Group),())';    
EXEC sp_executesql @sqlEAST;

Demo