Oracle SQL查询层次结构计数

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (32)

我有2个表1-部门(一些部门是其他部门的一部分)。 2名员工,在部门工作

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

我需要找到每个部门的员工人数,包括父母。我想我必须使用“connect by”功能,但我不知道如何使用它。结果是:

ID  Qty
1   1
2   3
3   1
4   1
提问于
用户回答回答于

如您所怀疑,需要CONNECT BY。 诀窍是省略START WITH子句,因此每个部门都被视为“根”。 然后,我们可以计算每个“root”的员工 - 即每个部门及其所有子部门。

这是你的例子。 我还为您的部门结构添加了一个额外的级别,作为一个更高级的测试用例。

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 | +----------+----------+----------------------------+

扫码关注云+社区

领取腾讯云代金券