Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hierarchical query and counting siblings?

I've looked at several different answers on this site and others, but I'm not having much luck figuring out how to count siblings in a hierarchical query.

I'm using 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

This returns 4 levels, and about 80 employees. I'm wanting to add up the number of siblings under the level 2 instead of listing them all. But, I'm getting stuck trying to figure it out.

Any nudges towards the right way? Thanks!

like image 922
Jake_TheCoder Avatar asked Oct 15 '25 19:10

Jake_TheCoder


1 Answers

This will count the number of descendents of each employee at level 1 and 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;
like image 129
Jon Heller Avatar answered Oct 19 '25 12:10

Jon Heller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!