Doing a concat over a partition in SQL?

╄→尐↘猪︶ㄣ 提交于 2021-01-27 13:29:57

问题


I have some data ordered like so:

date, uid, grouping
2018-01-01, 1, a
2018-01-02, 1, a
2018-01-03, 1, b
2018-02-01, 2, x
2018-02-05, 2, x
2018-02-01, 3, z
2018-03-01, 3, y
2018-03-02, 3, z

And I wanted a final form like:

uid, path
1, "a-a-b"
2, "x-x"
3, "z-y-z"

but running something like

select
a.uid
,concat(grouping) over (partition by date, uid) as path
from temp1 a

Doesn't seem to want to play well with SQL or Google BigQuery (which is the specific environment I'm working in). Is there an easy enough way to get the groupings concatenated that I'm missing? I imagine there's a way to brute force it by including a bunch of if-then statements as custom columns, then concatenating the result, but I'm sure that will be a lot messier. Any thoughts?


回答1:


You are looking for string_agg():

select a.uid, string_agg(grouping, '-' order by date) as path
from temp1 a
group by a.uid;


来源:https://stackoverflow.com/questions/50338052/doing-a-concat-over-a-partition-in-sql

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