我正在使用SQL Server 2005和VS 2008.我正在查询如下所示
SELECT Month
, SUM(Man) AS Man
, SUM(Sal) AS Sal
, SUM(Man + Sal) AS Total
FROM (
SELECT DATENAME(MONTH, DOB) AS Month
, CASE WHEN TypeOfPost = 'Manager' THEN 1 ELSE 0 END AS Man
, CASE WHEN TypeOfPost = 'Sales' THEN 1 ELSE 0 END AS Sal
FROM tableName
) g
GROUP BY
Month
生成以下输出
Output--
-------------------------------------
Month Man Sal Total
-------- ----- ------ ---------
January 1 1 2
June 1 NULL 1
November 1 1 2
但现在我想计算Total column的总数。所以我帮帮忙。
Expected Output--
-------------------------------------
Month Man Sal Total
-------- ----- ------ -------
January 1 1 2
June 1 NULL 1
November 1 1 2
-------------------------------------
Total 5
-------------------------------------
答案 0 :(得分:5)
您可以使用WITH ROLLUP
中的GROUP BY
选项 - 这会为您提供一个额外的行,其中包含“累计”(总结)值:
SELECT Month
, SUM(Man) AS Man
, SUM(Sal) AS Sal
, SUM(Man + Sal) AS Total
FROM (
SELECT DATENAME(MONTH, DOB) AS Month
, CASE WHEN TypeOfPost = 'Manager' THEN 1 ELSE 0 END AS Man
, CASE WHEN TypeOfPost = 'Sales' THEN 1 ELSE 0 END AS Sal
FROM tableName
) g
GROUP BY
Month WITH ROLLUP
额外的行将包含NULL
列的Month
,并且应该为您汇总所有其他列