在开发过程中,经常会有产品剔除需要将整体数据与拆分维度的数据放在一起,可能会有人想到将不同维度group by 的数据union all在一起,但这样效率比较低。使用grouping sets相当于是将不同维度group by的数据union all,对于不在聚合维度里的列,可以使用coalesce将null值转为你想要的描述。
比如,需要将分国内海外和星级的数据与分国内海外不分星级的整体数据,放在一起。分国内海外星级的数据使用 group by countryflag ,star ,而只区分国内海外的使用group by countryflag,不区分星级的话,star字段为NULL,可以使用coalesce转为“整体”。
select
case when country = '中国' then '国内'
when country<> '中国' then '海外'
else '未知' end as countryflag
,coalesce(star,'整体') as star -- 这种写法要确保star原本没有NULL值
,stddev(height) as std_height
from
(
select a.cid
,a.sid
,a.pvid
,a.masterhotelid
,a.page
,a.hotelcardheight
,case when b.starlevel >= 4 then '高星'
else '低星' end as star
from db.table
) a
group by countryflag ,star
grouping sets( (countryflag ),
(countryflag ,star) )