我需要扩展我的sql查询,返回子总数和&总计。有没有办法通过此查询返回子总计和总计:
我有这样的数据:
Department Employee Sal
A Jack 1000
A Pack 1000
A Dack 1000
B BEN 1000
B HEN 1000
C SIN 1000
我想要这个,即小计&所有部门的总数
Department Employee Sal
A Jack 1000
A Pack 1000
A Dack 1000
A_Sub_Total 3000
B BEN 1000
B MAT 1000
B_Sub_Total 2000
C SIN 1000
C_Sub_Total 1000
Total 6000
我尝试使用计算功能,即"计算总和(Sal)由部门" 它无法正常工作
答案 0 :(得分:0)
试试这个:
SELECT [Department], [Employee], [Sal]
FROM #mytable
UNION ALL
SELECT [Department] + '_Sub_Total',
NULL,
SUM([Sal]) AS Sal
FROM #mytable
GROUP BY [Department]
UNION ALL
SELECT 'Total', NULL, SUM([Sal]) AS Sal
FROM #mytable
ORDER BY Department
答案 1 :(得分:0)
您可以使用WITH ROLLUP。
SELECT ISNULL(Department, 'Total'), ISNULL(Employee, Department + '_Sub_Total'), SUM(Sal) AS Sal FROM [test] GROUP BY Department, Employee WITH ROLLUP