2016-03-22 255 views
0

我需要擴展我的sql查詢,返回小計&總計。有沒有辦法與該查詢返回兩個子總數和總計:小計和總計總計

我有這樣的數據:所有部門

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 

Department Employee Sal 
A   Jack  1000   
A   Pack  1000   
A   Dack  1000   
B   BEN  1000   
B   HEN  1000   
C   SIN  1000 

我想這一點,即小計&總

我試圖使用計算功能,即「部門計算總和(薩爾)」 它不工作

回答

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 
0

您可以使用WITH ROLLUP。

SELECT ISNULL(Department, 'Total'), ISNULL(Employee, Department + '_Sub_Total'), SUM(Sal) AS Sal FROM [test] GROUP BY Department, Employee WITH ROLLUP