分层查询和计数兄弟姐妹?

时间:2012-09-25 01:43:16

标签: oracle10g hierarchical

我已经在这个网站和其他网站上看了几个不同的答案,但我没有太多运气搞清楚如何在分层查询中统计兄弟姐妹。

我正在使用Oracle 10g。

SELECT LEVEL, last_name||', '||first_name AS Manager, count(employee_id)
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
GROUP BY level

这将返回4个级别,约80名员工。我想把2级以下的兄弟姐妹的数量加起来而不是列出所有兄弟姐妹。但是,我一直在努力解决这个问题。

任何朝着正确方向的推动?谢谢!

1 个答案:

答案 0 :(得分:1)

这将计算每个员工在1级和2级的后代数量:

SELECT employee_id, manager_id, full_name, emp_level
    ,(
        SELECT COUNT(*)
        FROM employees
        START WITH employees.manager_id = employees2.employee_id
        CONNECT BY prior employee_id = manager_id
    ) descendents
FROM
(
    SELECT employee_id, manager_id, last_name||', '||first_name full_name, LEVEL emp_level
    FROM employees
    START WITH manager_id IS NULL
    CONNECT BY PRIOR employee_id = manager_id
) employees2
WHERE emp_level <= 2;