22,209
社区成员
发帖
与我相关
我的任务
分享
select
单位,
店家=CASe when GROUPING(店家)=1 then '累计' else 店家 end,
当天销售额=SUM(当天销售额),
今年累计销售额=SUM(今年累计销售额)
from tb
group by 单位,店家 with rollup
having GROUPING(单位)=0
/*
单位 店家 当天销售额 今年累计销售额
---------- ---------- ----------- -----------
a a1 50 400
a a2 70 700
a b1 10 900
a 累计 130 2000
b b1 10 944
b c1 8 899
b d1 300 459
b d2 24 900
b 累计 342 3202*/
--> 测试数据: @tb
declare @tb table (单位 varchar(1),店家 varchar(2),当天销售额 int,今年累计销售额 int)
insert into @tb
select 'a','a1',50,400 union all
select 'a','a2',70,700 union all
select 'a','b1',10,900 union all
select 'b','b1',10,944 union all
select 'b','c1',8,899 union all
select 'b','d1',300,459 union all
select 'b','d2',24,900
select
单位,
店家=case when 店家 is null then '累计' else 店家 end,
当天销售额=sum(case when 店家 is null then 当天销售额 else 当天销售额 end),
今年累计销售额=sum(case when 店家 is null then 今年累计销售额 else 今年累计销售额 end)
from @tb
group by 单位,店家
with rollup
having( 单位 is not null )
单位 店家 当天销售额 今年累计销售额
---- ---- ----------- -----------
a a1 50 400
a a2 70 700
a b1 10 900
a 累计 130 2000
b b1 10 944
b c1 8 899
b d1 300 459
b d2 24 900
b 累计 342 3202
(9 行受影响)
select
case when grouping(a)=1 then '合计' else cast(a as varchar) end a,
case when grouping(b)=1 and grouping(a)=0 then '小计' else cast(b as varchar) end b, sum(c) as c, sum(d) as d,sum(e) as e from #t
group by
a,b,c
with rollup
having grouping(a)=1 or grouping(b)=1 or grouping(c)=0
drop table #t
a b c d e
------------------------------ ------------------------------ ----------- ----------- -----------
1 2 12 16 26
1 3 12 16 26
1 小计 24 32 52
2 2 2 4 5
2 2 3 4 6
2 2 4 4 7
2 2 5 4 8
2 3 9 12 21
2 3 6 4 5
2 小计 29 32 52
合计 NULL 53 64 104
(所影响的行数为 11 行)
*/
create table tb(单位 varchar(10), 店家 varchar(10), 当天销售额 int, 今年累计销售额 int)
insert into tb values('a' , 'a1' , 50 , 400)
insert into tb values('a' , 'a2' , 70 , 700)
insert into tb values('a' , 'b1' , 10 , 900)
insert into tb values('b' , 'b1' , 10 , 944)
insert into tb values('b' , 'c1' , 8 , 899)
insert into tb values('b' , 'd1' , 300 , 459)
insert into tb values('b' , 'd2' , 24 , 900)
go
select * from
(
select * from tb
union all
select 单位 , 店家 = '累计' , sum(当天销售额) 当天销售额, sum(今年累计销售额) 今年累计销售额 from tb group by 单位
) t
order by 单位 , case 店家 when '累计' then 2 else 1 end
drop table tb
/*
单位 店家 当天销售额 今年累计销售额
---------- ---------- ----------- -----------
a a1 50 400
a a2 70 700
a b1 10 900
a 累计 130 2000
b d2 24 900
b c1 8 899
b d1 300 459
b b1 10 944
b 累计 342 3202
(所影响的行数为 9 行)
*/
select * from
(
select * from tb
union all
select 单位 , 店家 = '累计' , sum(当天销售额) 当天销售额, sum(今年累计销售额) 今年累计销售额 from tb group by 单位
) t
order by 单位 , case 店家 when '累计' then 2 else 1 end