分组集,汇总但具有多列

Grouping Sets, Roll-up but with multiple columns

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

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

如果我执行以下操作并排除此人,我会得到总计,但我还需要显示此人:

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

这是怎么做到的?

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

您可以使用 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

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

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