【SQL】sql 总计、小计,汇总中的所有组合;关于rollup/cube/grouping sets/grouping全总结

本文介绍了如何利用SQL实现类似Excel透视表的功能,包括GROUPINGSETS、WITHROLLUP和WITHCUBE三种方法,用于多维度汇总数据。GROUPINGSETS允许指定任意组合进行分组,WITHROLLUP提供递进式层级分组,而WITHCUBE则对所有可能的组合进行分组。此外,还展示了如何使用GROUPING函数处理汇总行的NULL值,以得到更清晰的汇总结果。

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

数据分析中常常需要各种不同维度的汇总,下面介绍如何让sql像excel透视表一样汇总,可以节省不少行代码

使用条件:必须与group by一起使用,放在group by 之后
优化:汇总行会出现null值,需要用到grouping一步修改null值

三种汇总区别:
grouping sets : 指定任意组合进行分组;
with rollup: 递进式层级进行分组,因此group by 后的字段顺序不同会有不同的分组结果
with cube: 对每个可能的组合分组。

GROUPING SETS

select channel
,isconfirm
,star 
,count(distinct orderid) sales

from talble

group by channel
,isconfirm
,star 

grouping sets(channel,isconfirm,(star,isconfirm))

在这里插入图片描述
等价于:

select channel,NULL,NULL
,count(distinct orderid) sales
from table 
group by channel

union all 

select NULL,isconfirm,NULL
,count(distinct orderid) sales
from table 
group by isconfirm

union all 

select NULL,isconfirm,star
,count(distinct orderid) sales
from table 
group by isconfirm,star

WIHT ROLLUP

select channel
,isconfirm
,star 
,count(distinct orderid) sales

from talble

group by channel
,isconfirm
,star 

with rollup

下钻过程:总体→channel→channel+isconfrim
在这里插入图片描述
调换group by之后的字段顺序,分组也发生了改变

select channel
,isconfirm
,star 
,count(distinct orderid) sales

from talble

group by star 
,isconfirm
,channel

with rollup

下钻过程:总体→star→star+isconfirm
在这里插入图片描述
WITH CUBE

所有可能的分组

select channel
,isconfirm
,star 
,count(distinct orderid) sales

from talble

group by channel
,isconfirm
,star 

with cube

在这里插入图片描述
用grouping 修改NULL值

select if(grouping(channel)=1,'整体',channel) channel
,if(grouping(isconfirm)=1,'整体',isconfirm) isconfirm
,if(star)=1,'整体',star) star
,count(distinct orderid) sales

from talble

group by channel
,isconfirm
,star 

with cube

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值