2015-11-10 76 views
0

我在SQL Server 2014中,我有一個列表ID與各種總計列。我想爲該建築添加一排總計。TSQL:如何添加總計行

可以在SQL中完成以下所需的輸出嗎?如果是這樣,最好的方法是什麼?我需要學習如何爲各種項目。我不需要LevelID總計,僅用於其他列,而且我不確定是否可以在總計行中添加文本「BuildingTotal」。

所需的輸出:

enter image description here

SQL Fiddle:

這裏是萬一測試表SQL小提琴不起作用的代碼。

CREATE TABLE EMPLOYEES 
(
BuildingID Numeric, 
LevelID Numeric, 
FemaleEmp Numeric, 
MaleEmp Numeric, 
TotalEmpByLevel Numeric 
) 

INSERT INTO EMPLOYEES 
(BuildingID, LevelID, FemaleEmp, MaleEmp, TotalEmpByLevel) 
VALUES 
(111, 1,91, 89, 180), 
(111, 2,98, 94, 192), 
(111, 3,94, 113 , 207), 
(111, 4,110, 119, 229), 
(111, 5,107, 9, 203), 
(113, 1,53, 4, 101), 
(113, 2,51, 5, 106), 
(113, 3,68, 5, 119), 
(113, 4,58, 6, 118), 
(113, 5,57, 6, 117), 
(114, 1,25, 3, 56), 
(114, 2,26, 3, 63), 
(114, 3,32, 2, 61), 
(114, 4,27, 3, 58), 
(114, 5,26, 2, 49), 
(116, 1,84, 102 , 186), 
(116, 2,83, 92, 175), 
(116, 3,89, 87, 176), 
(116, 4,71, 91, 162), 
(116, 5,87, 72, 159) 

謝謝你的幫忙!通過用匯總

這是link與例如

+1

DO(選擇... UNION ALL用組選)ORDER BY ... – jarlh

回答

2

的一種方法是使用分組集或與彙總

+0

觀看演示https://開頭data.stackexchange.com/stackoverflow/query/388044。你需要使用'分組(LevelId)'不'分組(BuildingId)' – lad2025

+0

謝謝@Gordon Linoff !.分組部分工作。 – JM1

+1

@ lad2025,您在levelid分組上是正確的。謝謝! – JM1

2

嘗試組。不過,這需要一些小技巧。您需要聚合查詢:

select BuildingId, LevelId, sum(FemaleEmp) as FemaleEmp, 
     sum(MaleEmp) as MaleEmp, sum(TotalEmpByLevel) as TotalEmpByLevel 
from employees 
group by grouping sets((BuildingId, LevelId), (BuildingId)); 

您可以將字Total添加到行中。這是一個有點棘手,因爲類型不同:

select (case when grouping(LevelId) = 1 then 'Building Total' else cast(BuildingId as varchar(255)) end) as BuildingId, 
     LevelId, sum(FemaleEmp) as FemaleEmp, 
     sum(MaleEmp) as MaleEmp, sum(TotalEmpByLevel) as TotalEmpByLevel 
from employees 
group by grouping sets((BuildingId, LevelId), (BuildingId)); 
+0

歡迎您:) – starko