如何在带有动态列的SQL中使用SUM函数

时间:2018-07-16 13:02:31

标签: sql sql-server

我已将Dynamic PIVOT的结果安排到Tem​​p Table中,如下所示:

--------------------------------------------------------
| City        | 2018-07-14 | 2018-07-15  |  2018-07-16 |
--------------------------------------------------------
| Satara      |     3      |      9      |      1      |
| Maharashtra |     0      |      4      |      1      |
| Ghatkopar   |     10     |      1      |      1      |
--------------------------------------------------------

预期输出:

----------------------------------------------------------------------
| City        |  2018-07-14 | 2018-07-15 | 2018-07-16 |    Total     |
---------------------------------------------------------------------
| Satara      |   3         |     9      |      1     |      13      |
| Maharashtra |   0         |     4      |      1     |      5       |
| Ghatkopar   |   10        |     1      |      1     |      12      |
----------------------------------------------------------------------
 NULL         |   13        |     14    |      3      |      30      |
--------------------------------------------------------------------

最后三列是日期,该日期是动态Today's Date - 3 Days

1 个答案:

答案 0 :(得分:1)

您可以使用GROUP BY ROLLUP来获取垂直总计。在此示例中,我将Total作为计算列进行计算,但您可以在枢轴之前进行汇总。

DECLARE @tbl TABLE (City VARCHAR(25), [2018-07-14] int, [2018-07-15] int, 
    [2018-07-16] int, Total AS [2018-07-14] + [2018-07-15] + [2018-07-16])

INSERT INTO @tbl VALUES ('Satara', 3, 9, 1)
INSERT INTO @tbl VALUES ('Maharashtra', 0, 4, 1)
INSERT INTO @tbl VALUES ('Ghatkopar', 10, 1, 1)

SELECT City, SUM([2018-07-14]) AS [2018-07-14], 
    SUM([2018-07-15]) AS [2018-07-15], 
    SUM([2018-07-16]) AS [2018-07-16],
    SUM(Total) AS Total
FROM @tbl
GROUP BY ROLLUP (City);

返回:

City        2018-07-14  2018-07-15  2018-07-16  Total
Ghatkopar   10          1           1           12
Maharashtra 0           4           1           5
Satara      3           9           1           13
NULL        13          14          3           30

如果您担心动态列标题,可以使用动态sql以编程方式更改它们:

DECLARE @D1 VARCHAR(10) = FORMAT(GETDATE() - 2, 'yyyy-MM-dd')
DECLARE @D2 VARCHAR(10) = FORMAT(GETDATE() - 1, 'yyyy-MM-dd')
DECLARE @D3 VARCHAR(10) = FORMAT(GETDATE(), 'yyyy-MM-dd')

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT City, SUM([' + @D1 + ']) AS [' + @D1 + '], 
    SUM([' + @D2 + ']) AS [' + @D2 + '], 
    SUM([' + @D3 + ']) AS [' + @D3 + '],
    SUM([' + @D1 + '] + [' + @D2 + '] + [' + @D3 + ']) AS Total
FROM tbl
GROUP BY ROLLUP (City);'

EXEC sp_executesql @SQL