透视列Postgresql

时间:2016-09-26 00:48:34

标签: sql postgresql pivot-table snowflake

我有一个看起来像这样的表:

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

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

total_units_per_username    item_name               frequency
3                        phone, laptop, watch      1

基本上我想转动item_name列,连接total_units_per_username上的所有值,并计算该事件的频率。我使用Snowflake。

谢谢!

1 个答案:

答案 0 :(得分:0)

我想你想要两个聚合:

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;
相关问题