GreenPlum[postgreSQL]之-Grouping Sets、grouping()函式、cube方式
阿新 • • 發佈:2021-01-09
技術標籤:GreenPlum
GreenPlum[postgreSQL]之-Grouping Sets
前言
grouping sets是為了簡化程式碼而設計的一種風格,通常可以將不同緯度的統計資料放在同一個檢視或者表中,有點類似於cube立方體的風格。
參考網址:https://www.postgresqltutorial.com/postgresql-grouping-sets/
1 需求
現有以下資料,其中brand\segment
是緯度,我們需要根據這2個緯度算出所有維度組合下的所有的sum()度量metrix
。
DROP TABLE IF EXISTS sales;
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);
需求目標如下,展示以下資料。
2 實現方式
2.1 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 ;
2.2 grouping sets的方式
--很明顯程式碼簡潔了許多,如果緯度組合較多,那麼這種方式會更加方便簡潔
select brand,segment,sum(quantity) from sales
group by grouping sets((brand,segment),(brand),(segment),())
2.3 grouping 方法
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
2.4 cube方式
除了grouping sets可以動態選擇不同的維度組合,cube自動選擇所有的維度組合,構建多維模型。
select brand,segment,sum(quantity) from sales
group by cube(brand,segment)--[,another_dimensions......]