我有一个看起来像这样的表:
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。
谢谢!
答案 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;