雪花:基于条件的ListAgg数据

问题描述

我有一个表格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,Mac
3  |   3    | Mac     | Linux,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,Mac
3  |   0    | Windows
3  |   3    | Linux,Mac

如何更改此查询获取所需的输出

解决方法

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

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