CREATE TABLE sales ( brand VARCHAR NOT NULL, segment VARCHAR NOT NULL, quantity
INT NOT NULL, PRIMARY KEY (brand, segment) ); INSERT INTO sales (brand, segment,
quantity) VALUES ('ABC', 'Premium', 100), ('ABC', 'Basic', 200), ('XYZ',
'Premium', 100), ('XYZ', 'Basic', 300);
<>union all的实现
select brand,segment,sum(quantity) from sales group by brand,segment union all
select brand,null,sum(quantity) from sales group by brand union all select null,
segment,sum(quantity) from sales group by segment union all select null,null,sum
(quantity) from sales ;
<>grouping sets实现
select coalesce (brand,'所有品牌') brand,coalesce(segment,'所有类型') segment,sum(
quantity) from sales group by grouping sets((brand,segment),(brand),(segment),()
)
pg既然提供了grouping sets,就提供了对应了对应的grouping()函数,用来判断是否该纬度在该指标统计中是否被用到

用到,返回0
没用到,返回1
select grouping(brand) as brand_used, grouping(segment) as segment_used, brand,
segment, sum(quantity) from sales group by grouping sets((brand,segment),(brand
),(segment),()) having grouping(brand) = 1

技术
今日推荐
PPT
阅读数 135
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信