Oracle Sql - retrieve distinct data from a listagg [duplicate]

余生长醉 提交于 2019-12-11 16:53:58

问题


With this command I'm able to retrieve a count of all the distinct manager_id grouped by department_id

select department_id, count( distinct manager_id) 
from employees
group by department_id

If I want to see a list of those managers, I can use this but the problem is that they are repeated and not distinct

select 
    department_id,
    listagg(manager_id, ' | ') within group(order by manager_id)
from  
    employees
group by 
    department_id;

This outputs a long list of repeated manager_id.

One row example:

100 | 100 | 100 | 100 | 100 | 120 | 120 | 120 | 120 | 120 | 120 | 120 | 120 | 121 | 121 | 121 | 121 | 121 | 121 | 121 | 121 | 122 | 122 | 122 | 122 | 122 | 122 | 122 | 122 | 123 | 123 | 123 | 123 | 123 | 123 | 123 | 123 | 124 | 124 | 124 | 124 | 124 | 124 | 124 | 124

I want to be able to have a list of unique manager_ids, not repeating like the above one. How should I do this ?


回答1:


You can use a subquery to remove duplicates:

select department_id, count(*),
       listagg(manager_id, ' | ') within group (order by manager_id)
from (select distinct department_id, manager_id
      from employees
     ) e
group by department_id


来源:https://stackoverflow.com/questions/48046154/oracle-sql-retrieve-distinct-data-from-a-listagg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!