在 PostgreSQL 中使用 SQL 在组内创建集

问题描述 投票:0回答:1

我正在尝试从现有行创建集合,但遇到困难。我取得了一些成功,但没有达到我的预期。

这是我现有的数据和我想要的结果。我尝试了很多分组和窗口功能,但无法找到解决方案。

**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
sql postgresql grouping
1个回答
0
投票

您需要取消嵌套标志并通过

(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"

db<>fiddle 中测试它。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.