首页 > 解决方案 > oracle sql中的listagg

问题描述

我在 Oracle 中有这个 sql 查询:

SELECT listagg(A.name, ",") within group (ORDER BY A.id) as A,
listagg(B.name, ",") within group (ORDER BY B.id) as B
FROM some_table
join A on A.id = some_table.id
join B.name = some_table.name
where some_table.status in (1,2,3)
group by some_table.id

我的问题是我从不想要的 listagg 中得到重复的结果。我该如何解决?谢谢!

标签: sqloraclelistagg

解决方案


Oracle 不支持distinctOracle listagg()19 之前的版本。

但是,在您的情况下,问题可能是由笛卡尔积引起的joins. 这表明相关子查询是一种更好的方法:

select t.*,
       (select listagg(a.name, ',') within group (order by a.id)
        from A a
        where a.id = t.id 
       ) as a,
       (select listagg(b.name, ',') within group (order by b.id)
        from B b
        where b.id = t.id 
       ) as b
from some_table t
where t.status in (1, 2, 3)
group by t.id;

推荐阅读