旋转列 Postgresql

Pivoting column Postgresql

我有一个 table 看起来像这样:

username     item_name   total_units_per_username    
abc@gma.com   laptop      2
abc@gma.com   watch       2
xyz@gma.com  phone        3
xyz@gma.com  laptop       3
xyz@gma.com  watch        3

我想要一个 table 看起来像这样的:

total_units_per_username    item_name               frequency
3                        phone, laptop, watch      1

基本上我想旋转 item_name 列,连接 total_units_per_username 上的所有值,并计算该列出现的频率。我正在使用雪花。

谢谢!

我想你想要两个聚合:

select numitems, items, count(*) as freq
from (select username,
             string_agg(item_name order by item_name, ', ') as items,
             count(*) as numitems
      from t
      group by username
     ) t
group by numitems, items;

编辑:

您也可以使用 array_agg():

select numitems, items, count(*) as freq
from (select username,
             array_agg(item_name order by item_name) as items,
             count(*) as numitems
      from t
      group by username
     ) t
group by numitems, items;