Zzema
Zzema

Reputation: 307

Oracle SQL query hierarchy counts

I have 2 tables 1- departments (some departments are part of other department).
2- employees, which works in departments

WITH `d1` AS (
      SELECT 1 ID, 'dep1' NAME,    null Parent_id UNION ALL
      SELECT 2, 'dep2',           null             UNION ALL
      SELECT 3, 'dep21',  2                UNION ALL
      SELECT 4,'dep22',                 2 
    )
WITH `d2` AS (
  SELECT 1 ID, 'Name1' NAME,    3 DEP_id UNION ALL
  SELECT 2,         'Name2',    4             UNION ALL
  SELECT 3,         'Name3',     1               UNION ALL
  SELECT 4,         'Name4',    2             UNION ALL

I need to find the number of employees in each department, including the parent. Ithink I have to use "connect by" function, but I don't know how I can use it. The result is:

ID  Qty
1   1
2   3
3   1
4   1

Upvotes: 0

Views: 242

Answers (1)

Matthew McPeak
Matthew McPeak

Reputation: 17924

CONNECT BY is required, as you suspected. The trick is to omit the START WITH clause, so every department is treated as a "root". Then, we can count the employees for each "root" -- i.e., for each department and all its sub-departments.

Here is your example, again. I also added an additional level to your departments structure, as a more advanced test-case.

WITH dept ( id, name, parent_id) AS (
      SELECT 1, 'dep1', null FROM DUAL UNION ALL
      SELECT 2, 'dep2', null FROM DUAL UNION ALL
      SELECT 3, 'dep21',  2 FROM DUAL  UNION ALL
      SELECT 4,'dep22', 2 FROM DUAL UNION ALL
      SELECT 5, 'dep211', 3 FROM DUAL
    ),
 emp (id, name, dep_id) AS (
  SELECT 1, 'Name1', 3 FROM DUAL UNION ALL
  SELECT 2, 'Name2', 4 FROM DUAL UNION ALL
  SELECT 3, 'Name3', 1 FROM DUAL  UNION ALL
  SELECT 4, 'Name4', 2 FROM DUAL UNION ALL 
  SELECT 5, 'Name5', 5 FROM DUAL
),
intermediate as (
select connect_by_root d.name deptname, level lvl, e.id empid, e.name empname
from dept d left join emp e on e.dep_id = d.id
-- Unfortunately, connecting this way, we cannot also determine the "level" of each 
-- department.  To do that, we would need the CONNECT BY to be reversed, i.e.,: 
-- connect by prior d.parent_id = d.id
connect by d.parent_id = prior d.id
-- No "START WITH" clause
)
SELECT deptname, 
       count(empid) empcount,
       listagg(empname,', ') within group ( order by empname) emplist
FROM intermediate
GROUP BY deptname
ORDER BY deptname;
+----------+----------+----------------------------+
| DEPTNAME | EMPCOUNT |          EMPLIST           |
+----------+----------+----------------------------+
| dep1     |        1 | Name3                      |
| dep2     |        4 | Name1, Name2, Name4, Name5 |
| dep21    |        2 | Name1, Name5               |
| dep211   |        1 | Name5                      |
| dep22    |        1 | Name2                      |
+----------+----------+----------------------------+

Upvotes: 1

Related Questions