sql 中的grouping函数

本文介绍了一段SQL代码示例,展示了如何使用Rollup进行分组汇总,并结合Case...When...Then语句和Grouping函数来实现不同层级的数据汇总,包括总览和特定分组的数据汇总。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ExpandedBlockStart.gif代码
declare @Temp table(Code varchar(10), ID int, SInt int)
insert into @Temp(Code, ID, SInt)
select '01',1,3
union
select '01',2,3
union
select '01',2,3
union
select '02',1,3
union
select '02',3,5
union
select '02',2,6
union
select '03',3,5
union
select '03',1,6

select case when grouping(code)=1 then 'Grand Total:'
            
when grouping(ID)=1 then Code+' Total:'
            
else Code
       
end as LevelCode, ID, SUM(Sint) as S
from @Temp
group by Code, ID
with rollup

这里面的

case when grouping(code)=1 then 'Grand Total:'
            when grouping(ID)=1 then Code+' Total:'
            else Code
       end as LevelCode
when的顺序是按照group by 里面的字段顺序。

转载于:https://www.cnblogs.com/lfzwenzhu/archive/2010/12/08/1899993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值