SELECT c.company_code, c.founder,
COUNT(DISTINCT(l.lead_manager_code)),
COUNT(DISTINCT(s.senior_manager_code)),
COUNT(DISTINCT(m.manager_code)),
COUNT(DISTINCT(e.employee_code))
FROM Company c
JOIN Lead_Manager l ON c.company_code = l.company_code
JOIN Senior_Manager s ON l.lead_manager_code = s.lead_manager_code
JOIN Manager m ON s.senior_manager_code = m.senior_manager_code
JOIN Employee e ON m.manager_code = e.manager_code
GROUP BY 1, 2
ORDER BY c.company_code
;
SQL
๋ณต์ฌ
์ค๋ณต ์์ด ์ธ๊ธฐ ์ํด์๋ count(distinct(COL))
C1 Angela 1 2 5 13
C10 Earl 1 1 2 3
C100 Aaron 1 2 4 10
C11 Robert 1 1 1 1
C12 Amy 1 2 6 14
SQL
๋ณต์ฌ
๋ชจ๋ฒ ๋ต์
SELECT c.company_code, c.founder,
COUNT(DISTINCT(l.lead_manager_code)),
COUNT(DISTINCT(s.senior_manager_code)),
COUNT(DISTINCT(m.manager_code)),
COUNT(DISTINCT(e.employee_code))
FROM Company c
LEFT JOIN Lead_Manager l ON c.company_code = l.company_code
LEFT JOIN Senior_Manager s ON l.lead_manager_code = s.lead_manager_code
LEFT JOIN Manager m ON s.senior_manager_code = m.senior_manager_code
LEFT JOIN Employee e ON m.manager_code = e.manager_code
GROUP BY 1, 2
ORDER BY c.company_code
;
SQL
๋ณต์ฌ
์ค๋ณต ์์ด ์ธ๊ธฐ ์ํด์๋ count(distinct(COL))
count๋ null์ ์ธ์ง ์๋๋ค.
๊ทธ๋ฆฌ๊ณ LEFT JOIN์ ํตํด ์ผ์ชฝ ๋์ ์ค์ฌ์ผ๋ก join ํ๋ค
๊ฐ ์กฐ์ธ๋๋ ์ผ์ชฝ ๋์ ์ค์ฌ์ผ๋ก ์์๊ฐ ์ฐํ ๊ฒ์ด๋ค
1 2
1 NULL
2 3
c.company_code๋ฅผ ๊ธฐ์ค์ผ๋ก count distinct๋ฅผ ํ๊ฒ ๋๋ฉด
๊ฐ ์กฐ์ธ ์์ ๋๋ ์์ ์์์ ๊ณ ์ ๊ฐ์๋ฅผ ์ธ์ฃผ๊ฒ ๋๋ค