TSQL:如何添加总计行

时间:2015-11-10 13:15:50

标签: sql sql-server tsql

我在SQL Server 2014上,我有一个包含各种总计列的建筑ID列表。我想为建筑添加一行总计。

可以在SQL中完成以下所需的输出吗?如果是这样,最好的方法是什么?我需要学习如何为各种项目。我不需要LevelID总计,仅针对其他列,我不确定是否可以添加文本' BuildingTotal'在总计行中。

期望输出:

enter image description here

SQL Fiddle:

如果SQL Fiddle不起作用,这是测试表的代码。

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)

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

尝试使用汇总分组

这是link示例

答案 1 :(得分: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));