现在,在Postgres的9.5版本中可以实现这一点:
PostgreSQL 9.5架构
CREATE TABLE basket(fruits text, a integer, b integer, c integer);
CREATE TABLE
INSERT INTO basket(fruits, a, b, c) values('apples', 1, 1, 1),
('apples', 0, 1, 2),
('bananas', 1, 1, 2),
('oranges', 1, 1, 1);
查询
SELECT coalesce(fruits,'total'), sum(a) a, sum(b) b, sum(c) c
FROM basket
GROUP BY ROLLUP((fruits))
结果
fruits | a | b | c
---------+---+---+---
apples | 1 | 2 | 3
bananas | 1 | 1 | 2
oranges | 1 | 1 | 1
total | 3 | 4 | 6
使用ROLLUP
与使用带有表达式的GROUPING SETS
等效:
SELECT fruits, sum(a) a, sum(b) b, sum(c) c
FROM basket
GROUP BY GROUPING SETS (fruits, ())
GROUPING SETS
中的每个子列表被解释为如果它直接出现在 GROUP BY 子句中一样。
UNION ALL
连接这两个查询(可能还需要转换你的值)。 - dezso