Aggregate string values to a list

久未见 提交于 2020-01-30 12:01:39

问题


I am trying to work some very simple logic to transform an unpivoted column into what essentially amounts to a grouped list. However, having troubles doing this efficiently.

Essentially, I have a data set that looks as follows:

CUST_ID     ORDER
1           Cake
1           Bread
2           Cake
3           Cake
3           Bread
3           Croissant
4           Croissant

But would like to output it as follows:

CUST_ID     ORDERS
1           Cake
1           Bread, Cake
3           Cake, Bread, Croissant
4           Croissant

I have tried subqueries (which I cannot get to work), but this seems brutal nonetheless:

SELECT CUST_ID, SELECT (ORDER FROM table GROUP BY CUST_ID)
FROM table
GROUP BY CUSTT_ID

Any ideas?


回答1:


Based on this SO question, Redshift now has a LISTAGG() analytic function which you can use.

SELECT CUST_ID,
       LISTAGG("ORDER", ', ')
WITHIN GROUP (ORDER BY "ORDER")
OVER (PARTITION BY CUST_ID) AS CUST_ID
FROM Table
ORDER BY CUST_ID


来源:https://stackoverflow.com/questions/43931929/aggregate-string-values-to-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!