手动实现ROLLUP
由于Redshift目前不支持ROLLUP子句,因此您必须以一种困难的方式来实现这种分组技术。
带一个参数的ROLLUP
使用ROLLUP,例如PostgreSQL
原始答案:Original Answer
SELECT column1, aggregate_function(*)
FROM some_table
GROUP BY ROLLUP(column1)
等价实现
DROP TABLE IF EXISTS tmp_totals;
CREATE TEMP TABLE tmp_totals AS
SELECT column1, aggregate_function(*) AS total1
FROM some_table
GROUP BY column1;
SELECT * FROM tmp_totals
UNION ALL
SELECT null, aggregate_function(total1) FROM tmp_totals
ORDER BY 1
最初的回答
示例输出
Country | Sales
-------- | -----
Poland | 2
Portugal | 4
Ukraine | 3
null | 9
带有两个参数的ROLLUP
使用ROLLUP,例如PostgreSQL
最初的回答:没有提供翻译
SELECT column1, column2, aggregate_function(*)
FROM some_table
GROUP BY ROLLUP(column1, column2);
等价的实现方式
DROP TABLE IF EXISTS tmp_totals;
CREATE TEMP TABLE tmp_totals AS
SELECT column1, column2, aggregate_function(*) AS total1
FROM some_table
GROUP BY column1, column2;
SELECT * FROM tmp_totals
UNION ALL
SELECT column1, null, sum(total1) FROM tmp_totals GROUP BY column1
UNION ALL
SELECT null, null, sum(total1) FROM tmp_totals
ORDER BY 1, 2;
Example output
Country | Segment | Sales
-------- | -------- | -----
Poland | Premium | 0
Poland | Base | 2
Poland | null | 2 <- sub total
Portugal | Premium | 1
Portugal | Base | 3
Portugal | null | 4 <- sub total
Ukraine | Premium | 1
Ukraine | Base | 2
Ukraine | null | 3 <- sub total
null | null | 9 <- grand total