【问题标题】:Snowflake: ListAgg data based on condition雪花:基于条件的 ListAgg 数据
【发布时间】:2020-12-15 20:00:28
【问题描述】:

我有一张桌子P,看起来像这样:

ID | Status | Env
1  |   1    | Linux
1  |   1    | Windows
1  |   3    | Mac
2  |   1    | Linux
2  |   1    | Windows
2  |   1    | Mac
3  |   3    | Linux
3  |   0    | Windows
3  |   3    | Mac

这里,1 表示测试成功,而任何其他数字都表示某种失败。我想以这样一种方式聚合这些数据,即对于每个失败的测试,我在每一行中都有一个以逗号分隔的失败环境列表。如果没有失败,新列中应该有NULL。输出看起来像

ID | Status | Env     | Failure_list
1  |   1    | Linux   | Mac
1  |   1    | Windows | Mac
1  |   3    | Mac     | Mac
2  |   1    | Linux   | Null
2  |   1    | Windows | Null
2  |   1    | Mac     | Null
3  |   3    | Linux   | Linux, Windows, Mac
3  |   0    | Windows | Linux, Windows, Mac
3  |   3    | Mac     | Linux, Windows, Mac

我在类似查询中使用雪花 LISTAGG() 函数

SELECT ID, STATUS, LISTAGG(ENV, ', ') 
FROM P
GROUP BY ID, STATUS

这是我得到的输出:

ID | Status | Env
1  |   1    | Linux, Windows
1  |   3    | Mac
2  |   1    | Linux, Windows, Mac
3  |   0    | Windows
3  |   3    | Linux, Mac

如何更改此查询以获得我正在寻找的输出?

【问题讨论】:

    标签: sql string subquery snowflake-cloud-data-platform window-functions


    【解决方案1】:

    您可以使用相关子查询来解决这个问题:

    select
        t.*,
        (
            select listagg(t1.env)
            from mytable t1
            where t1.id = t.id and t1.status <> 1
        ) failure_list
    from mytable t
    

    或者更好的是使用 listagg() 作为 Snowflake 支持的窗口函数:

    select 
        t.*,
        listagg(case when status <> 1 then env end) over(partition by id) failure_list
    from mytable t
    

    【讨论】:

    • 第二个查询非常适合我正在寻找的内容。
    • 您能否告诉我如何在雪花中更正以下查询..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-11-05
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多