• + 0 comments

    -- sol 1

    SELECT
        c.company_code,
        c.founder,
        COUNT(DISTINCT lm.lead_manager_code),
        COUNT(DISTINCT sm.senior_manager_code),
        COUNT(DISTINCT m.manager_code),
        COUNT(DISTINCT e.employee_code)
    FROM Company c
    JOIN Lead_Manager lm ON c.company_code = lm.company_code 
    JOIN Senior_Manager sm ON lm.lead_manager_code = sm.lead_manager_code
    JOIN Manager m ON sm.senior_manager_code = m.senior_manager_code
    JOIN Employee e ON m.manager_code = e.manager_code
    GROUP BY c.company_code, c.founder
    ORDER BY c.company_code
    -- A little trick for ORDER if you want the order like c1, c2, c3, ... You should use ORDER BY CAST(SUBSTRING(c.company_code, 2, LENGTH(c.company_code)) AS DECIMAL);
    

    -- sol 2

    SELECT
        c.company_code,
        c.founder,
        COUNT(DISTINCT e.lead_manager_code),
        COUNT(DISTINCT e.senior_manager_code),
        COUNT(DISTINCT e.manager_code),
        COUNT(DISTINCT e.employee_code)
    FROM Company c
    LEFT JOIN Employee e ON c.company_code = e.company_code
    GROUP BY c.company_code, c.founder
    ORDER BY c.company_code;
    

    -- sol 3

    SELECT
        c.company_code,
        c.founder,
        COUNT(DISTINCT lm.lead_manager_code),
        COUNT(DISTINCT sm.senior_manager_code),
        COUNT(DISTINCT m.manager_code),
        COUNT(DISTINCT e.employee_code)
    FROM Company c
    JOIN Lead_Manager lm ON c.company_code = lm.company_code
    JOIN Senior_Manager sm ON lm.company_code = sm.company_code
    JOIN Manager m ON sm.company_code = m.company_code
    JOIN Employee e ON m.company_code = e.company_code
    GROUP BY c.company_code, c.founder
    ORDER BY c.company_code