PostgreSQL ROLLUP 是group by 的子句,是生成多个分组集合的快捷功能。与Cube子句的差异是,rollup 不生成基于特定列所有可能的分组集合,生成分组集合为其子集。
ROLLUP假设输入列之间存在层次结构,从而生成有意义的所有分组集合。这就是为什么ROLLUP经常用于生成报表的小计和总计。
cube (c1,c2,c3)生成所有8中可能:
(c1, c2, c3)
(c1, c2)
(c2, c3)
(c1,c3)
(c1)
(c2)
(c3)
()
而ROLLUP(c1,c2,c3)仅生成4种分组集合,假设层级c1 > c2 > c3:
(c1, c2, c3)
(c1, c2)
(c1)
()
CREATE TABLE geeksforgeeks_courses(
course_name VARCHAR NOT NULL,
segment VARCHAR NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (course_name, segment)
);
INSERT INTO geeksforgeeks_courses(course_name, segment, quantity)
VALUES
('Data Structure in Python', 'Premium', 100),
('Algorithm Design in Python', 'Basic', 200),
('Data Structure in Java', 'Premium', 100),
('Algorithm Design in Java', 'Basic', 300);
select course_name,
segment,
SUM (quantity)
from geeksforgeeks_courses
group by (course_name, segment) order by course_name,segment
select course_name,
segment,
SUM (quantity)
from geeksforgeeks_courses
group by (course_name, segment)
union all
select course_name,
NULL,
SUM (quantity)
from geeksforgeeks_courses
group by (course_name)
union all
select NULL,
NULL,
SUM (quantity)
from geeksforgeeks_courses
order by course_name,segment
用如下的sql可以达到相同的效果
SELECT
course_name,
segment,
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP BY
ROLLUP (course_name, segment)
ORDER BY
course_name,
segment;
SELECT
coalesce(course_name,'所有课程'),
coalesce(segment,'所有'),
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP BY
ROLLUP (course_name, segment)
ORDER BY
course_name,
segment;
SELECT
coalesce(course_name,'所有课程'),
coalesce(segment,'所有'),
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP BY
cube (course_name, segment)
cube 分成了(), course_name,segment,course_name+segment
而rollup分成了(),course_name,course_name+segment
按照自定义进行分组
SELECT
coalesce(course_name,'所有课程'),
coalesce(segment,'所有'),
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP by GROUPING SETS ((course_name),(segment),(course_name,segment),())