问题
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