![](/img/trans.png)
[英]Pivoting a column based on sort order but with same name in PostgreSQL
[英]Pivoting column Postgresql
我有一个看起来像这样的表:
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上的所有值连接起来,并计算发生这种情况的频率。 我正在使用雪花。
谢谢!
我认为您需要两种汇总:
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()
进行此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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.