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
文章来源:https://www.toymoban.com/news/detail-592667.html
按照自定义进行分组文章来源地址https://www.toymoban.com/news/detail-592667.html
SELECT
coalesce(course_name,'所有课程'),
coalesce(segment,'所有'),
SUM (quantity)
FROM
geeksforgeeks_courses
GROUP by GROUPING SETS ((course_name),(segment),(course_name,segment),())
到了这里,关于4.postgresql--rollup,grouping sets,cube的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!