테이블 설명:
회사 코드에 해당하는 founder, lead manager, senior manager, manager, employee code을 불러오게 하는 쿼리를 작성하라
with founder as (
select e.*, c.founder
from Employee e
left join Company c on e.company_code =c.company_code )
select f.company_code ,
f.founder,
count(distinct(lead_manager_code)),
count(distinct(senior_manager_code)),
count(distinct(manager_code)),
count(distinct(employee_code))
from founder f
where f.company_code = (select company_code from Company)
WITH count_lead_m AS (
SELECT company_code ,COUNT(distinct (lead_manager_code)) as clm
FROM Lead_Manager
GROUP BY 1
),
WITH count_senior_m AS (
SELECT company_code ,COUNT(distinct (senior_manager_code)) as csm
FROM Senior_Manager
GROUP BY 1
),
WITH count_m AS (
SELECT company_code ,COUNT(distinct (manager_code)) as cm
FROM Manager
GROUP BY 1
),
WITH count_em AS (
SELECT company_code ,COUNT(distinct (employee_code)) as cem
FROM Employee
GROUP BY 1
)
SELECT company_code, founder, lm.clm, sm.csm, m.cm, em.cem
FROM Company c
left join count_lead_m lm on lm.company_code = c.company_code
left join count_senior_m sm on sm.company_code = c.company_code
left join count_m m on m.company_code = c.company_code
left join count_em em on em.company_code = c.company_code
생각하기
"employee table을 보면 생략된 senoir manager가 있어서
employee table에 founder를 합치면 안될거 같아" → 각 테이블은 company code가 있으므로, 각 테이블을 카운팅 하는게 맞을듯
WITH count_lead_m AS (
SELECT company_code, COUNT(DISTINCT lead_manager_code) AS clm
FROM Lead_Manager
GROUP BY company_code
),
count_senior_m AS (
SELECT company_code, COUNT(DISTINCT senior_manager_code) AS csm
FROM Senior_Manager
GROUP BY company_code
),
count_m AS (
SELECT company_code, COUNT(DISTINCT manager_code) AS cm
FROM Manager
GROUP BY company_code
),
count_em AS (
SELECT company_code, COUNT(DISTINCT employee_code) AS cem
FROM Employee
GROUP BY company_code
)
SELECT c.company_code, c.founder, lm.clm, sm.csm, m.cm, em.cem
FROM Company c
LEFT JOIN count_lead_m lm ON lm.company_code = c.company_code
LEFT JOIN count_senior_m sm ON sm.company_code = c.company_code
LEFT JOIN count_m m ON m.company_code = c.company_code
LEFT JOIN count_em em ON em.company_code = c.company_code
ORDER BY c.company_code