This question already has answers here:
LISTAGG in Oracle to return distinct values

(24个答案)


4年前关闭。




我有一个这样的表:
group_id  name
--------  ----
1         David
1         John
1         Alan
1         David
2         Julie
2         Charles

我想要以下结果:
group_id  names
--------  -----
1         'Alan, David, John'
2         'Charles, Julie'

我可以使用以下查询:
select group_id,
       listagg(name, ',') within group (order by name) as names
from demotable
group by group_id

要获得此结果(非常相似的结果):
group_id  names
--------  -----
1         'Alan, David, David, John'
2         'Charles, Julie'

有什么想法可以通过LISTAGG调用中的唯一性来过滤名称吗?

最佳答案

我今天没有11g实例,但是您不能使用:

SELECT group_id,
       LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
  FROM (
       SELECT UNIQUE
              group_id,
              name
         FROM demotable
       )
 GROUP BY group_id

08-06 21:47