问题
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