postgresql,命名分组集?

postgresql, named grouping sets?

有没有办法命名分组集?对于每个分组集(明确定义或根据 https://www.postgresql.org/docs/devel/static/queries-table-expressions.html 使用 rollup 或 cube 生成),我想以某种方式在结果列中指定一个名称。这是我正在尝试做的一个丑陋的即时演示,名称只是分组列的列表:

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 在这些组中为空。

有什么想法或更好的方法吗?

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);

Relevant documentation on grouping sets as per Clodoaldo Neto的回答。

Grouping Operations

Grouping operations are used in conjunction with grouping sets (see Section 7.2.4) to distinguish result rows. The arguments to the GROUPING operation are not actually evaluated, but they must match exactly expressions given in the GROUP BY clause of the associated query level. Bits are assigned with the rightmost argument being the least-significant bit; each bit is 0 if the corresponding expression is included in the grouping criteria of the grouping set generating the result row, and 1 if it is not.

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