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文章来源:https://www.toymoban.com/news/detail-579296.html
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
文章来源地址https://www.toymoban.com/news/detail-579296.html
到了这里,关于6.postgresql--grouping()的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!