善用Grouping Sets 提升代码效率

使用Grouping Sets可按照多个不同的维度组合进行聚合,减少了繁琐的代码,提升整体计算的效率。

比如,需要对国家,省份,城市各维度进行聚合时候,可能会这么写:

select '国家' as gep_type,country as geo_name,count(*) as cnt from tbl group by country
union all 
select '省份' as gep_type,province as geo_name,count(*) as cnt from tbl group by province
union all 
select '城市' as gep_type,city as geo_name,count(*) as cnt from tbl group by city
;

或者这么写:

select country,province,city,count(*)  as cnt from tbl group by country,province,city
union all
select country,province,'ALL' as city,count(*)  as cnt from tbl group by country,province
union all
select country,'ALL' as province,'ALL' as city,count(*)  as cnt from tbl group by country
;

无论哪种方式都会用到union all,而通过grouping sets,我们可以这么写:

-- 1. 先把空值替换成'-',不然在聚合的时候会被当成'ALL'
with tmp as (
    select 
        coalesce(country, '-') as country
        ,coalesce(province, '-') as province
        ,coalesce(city, '-') as city
    from tbl
)
-- 2.对于非本维度组合的字段,以'ALL'填充
select 
 coalesce(country, 'ALL') as country
,coalesce(province, 'ALL') as province
,coalesce(city, 'ALL') as city
,count(*)  as cnt 
from 
tmp 
group by country,province,city -- 按country,province,city聚合
grouping sets(
    (country) --只按country聚合,等于country,count(*)
    ,(province) --只按province聚合,等于province,count(*)
    ,(city) --只按city聚合,等于city,count(*)
    
    ,(country,province) --按country,province聚合,等于country,province,count(*)
) 

有任何疑问都可以在下方留言,我会尽量进行解答!

希望本文对你有帮助,请点个赞鼓励一下作者吧~ 谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王义凯_Rick

遇见即是缘,路过就给个评论吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值