有没有办法命名分组集?对于每个分组集(根据https://www.postgresql.org/docs/devel/static/queries-table-expressions.html明确定义或使用汇总或多维数据集生成),我想以某种方式在结果列中指定名称。这是我正在尝试做的一个丑陋的即时演示,名称只是分组列的列表:
select *, array_to_string(array_remove(array[case when "A" is null then null else 'A' end,
case when "B" is null then null else 'B' end,
case when "C" is null then null else 'C' end
],null),',') as grouping_set
from (values ('a','b','c'),
('aa','bb','cc'),
('aaa',null,'ccc')) as foo("A","B","C")
group by rollup(1,2,3);
A | B | C | grouping_set
-----+----+-----+--------------
a | b | c | A,B,C
a | b | | A,B
a | | | A
aa | bb | cc | A,B,C
aa | bb | | A,B
aa | | | A
aaa | | ccc | A,C <--------- should be A,B,C
aaa | | | A <--------- should be A,B
aaa | | | A
| | |
但请注意,其中两行存在问题,标有箭头:两者都包括分组中的B列但名称中没有,因为B在这些组中为空。
任何想法或更好的方法来解决这个问题?
答案 0 :(得分:3)
SELECT "A", "B", "C",
CASE GROUPING("A", "B", "C")
WHEN 0 THEN 'A,B,C'
WHEN 1 THEN 'A,B'
WHEN 3 THEN 'A'
ELSE ''
END AS grouping_set
FROM (VALUES ('a','b','c'),
('aa','bb','cc'),
('aaa',null,'ccc')
) AS foo("A","B","C")
GROUP BY ROLLUP(1,2,3);
答案 1 :(得分:2)
分组操作与分组集(参见第7.2.4节)结合使用,以区分结果行。 GROUPING操作的参数实际上没有被计算,但它们必须匹配关联查询级别的GROUP BY子句中给出的完全表达式。分配最右边的参数是最不重要的位;如果相应的表达式包含在生成结果行的分组集的分组标准中,则每个位为0;如果不是,则每个位为1。
select *, grouping("A","B","C") as grouping_set
from (values
('a','b','c'),
('aa','bb','cc'),
('aaa',null,'ccc')
) as foo("A","B","C")
group by rollup(1,2,3);
A | B | C | grouping_set
-----+----+-----+--------------
a | b | c | 0
a | b | | 1
a | | | 3
aa | bb | cc | 0
aa | bb | | 1
aa | | | 3
aaa | | ccc | 0
aaa | | | 1
aaa | | | 3
| | | 7