【发布时间】:2015-11-09 20:57:13
【问题描述】:
我正在尝试学习 SQL Server 2008 R2 中的 ROLLUP 和 GROUPING SETS 运算符。我的桌子是这样的:
我希望 EmpID 和 EmpName 显示每个员工一次,单位按类型小计,并按 EmpID、类型、帐户排序,如下所示:
+-------+---------+----------------+--------+------ ----+ |企业ID |员工姓名 |类型 |单位 |帐户 | +-------+---------+----------------+--------+------ ----+ | 11111 |爱丽丝 | | | | | | | CCS | 2.17 | 010.9055 | | | | CCS | 1.33 | 9P0.6010 | | | |小计 | 3.5 | | | | | SD20 | 0.5 | 560.2200 | | | | SD20 | 1 | 600.2200 | | | | SD20 | 4 | LP0.3002 | | | | SD20 | 1 | LP0.P303 | | | |小计 | 6.5 | | | 33333 |卡罗尔 | | | | | | | SD20 | 1 | 600.6P62 | | | | SD20 | 1 | 9P0.PP10 | | | | SD20 | 1 | P50.2100 | | | |小计 | 3 | | +-------+----------+----------------+--------+------ ----+这是我的查询
select
case
when Account is null and Type is null then cast(EmpID as varchar(10))
else ''
end SubEIN,
case
when Account is null and Type is null then EmpName
else ''
end SubName,
case
when Account is null and Type is not null then 'Subtotal:'
else isnull(Type, '')
end Type,
case
when Account is null and Type is null then ''
else cast(Units as varchar(10))
end Units,
isnull(Account, '')
from (
select EmpID, EmpName, Type, sum(Units) AS Units, Account
from mytable
group by grouping sets ((EmpID, EmpName), (EmpID, EmpName, Type), (EmpID, EmpName, Account, Type))
) x
order by x.EmpName, x.Type, x.Units, x.Account
我可以使用ROLLUP 和/或GROUPING SETS 运算符而不是所有CASE 表达式来获得我想要的吗?
【问题讨论】:
标签: sql-server sql-server-2008 sql-server-2008-r2