分组集,但具有多个列

时间:2019-05-12 00:39:39

标签: sql sql-server tsql rollup

我有一个查询,产生以下结果。我遇到的问题是如何在底部创建3行,显示> = 14天的总计,以及1-13天,然后是总计。

select
[Period],
[Person],
count(*) as NumberOfRecords,
sum([Amount]) as [Amount]

如果我执行以下操作,并且排除“人员”,我会得到一个总计,但我还需要该人员显示:

GROUP BY GROUPING SETS(([[Period]),());

这怎么办?

enter image description here

Create table #temp
(
    Period varchar(50),
    Person varchar(100),
    NumberOfRecords int,
    Amount money
)

insert into #temp
(
    Period,
    Person,
    NumberOfRecords,
    Amount
)
select
    '>= 14 days','',3,100
union all
select
    '>= 14 days','John Smith',32,200
union all
select
    '>= 14 days','Joe Bloggs',50,400
union all
select
    '>= 14 days','Jane Doe',52,750
union all
select
    '>= 14 days','Barry Knight',46,1000
union all
select
    '1-13 days','Bob the Builder',331,7500

2 个答案:

答案 0 :(得分:1)

您可以将ROLLUP用于小计。

SELECT
    CASE WHEN GROUPING(Period) = 1 THEN 'Total' ELSE Period END Period, 
    Person, SUM(NumberOfRecords) NumberOfRecords, 
    SUM(Amount) Amount 
from #temp
GROUP BY ROLLUP ((Period),(Period, Person))
ORDER BY GROUPING(Period), GROUPING(Person)

结果:

Period               Person               NumberOfRecords Amount
-------------------- -------------------- --------------- ---------------------
>= 14 days                                3               100.00
>= 14 days           Barry Knight         46              1000.00
>= 14 days           Jane Doe             52              750.00
>= 14 days           Joe Bloggs           50              400.00
>= 14 days           John Smith           32              200.00
1-13 days            Bob the Builder      331             7500.00
1-13 days            NULL                 331             7500.00
>= 14 days           NULL                 183             2450.00
Total                NULL                 514             9950.00

答案 1 :(得分:1)

尽管您可以使用ROLLUP,但我是GROUPING SETS的粉丝:

GROUP BY GROUPING SETS( (Period, Person), (Period), () );