我正在尝试从现有行创建集合,但遇到困难。我取得了一些成功,但没有达到我的预期。
这是我现有的数据和我想要的结果。我尝试了很多分组和窗口功能,但无法找到解决方案。
**Existing Data**
User Date Flags
John 2024-01-11 A,B,C
Doe 2024-01-15 A,B,C
John 2024-01-18 A,B,C,A,B,C
Doe 2024-01-25 A,B,C,A,B,C,A,B,C
**Desired Result**
User Date Flags
John 2024-01-11 A,B,C
Doe 2024-01-15 A,B,C
John 2024-01-18 A,B,C
John 2024-01-18 A,B,C
Doe 2024-01-25 A,B,C
Doe 2024-01-25 A,B,C
Doe 2024-01-25 A,B,C
您需要取消嵌套标志并通过
(user, date)
获取组内重复标志的序数,然后使用这些数字聚合数据。
select "user", "date", string_agg(flag, ',' order by flag) as flags
from (
select "user", "date", flag, row_number() over w
from my_table
cross join string_to_table("flags", ',') as f(flag)
window w as (partition by "user", "date", flag)
) s
group by "user", "date", row_number
order by "date", "user"