https://school.programmers.co.kr/learn/courses/30/lessons/59413
0์๋ถํฐ 23์๊น์ง, ๊ฐ ์๊ฐ๋๋ณ๋ก ์ ์์ด ๋ช ๊ฑด์ด๋ ๋ฐ์ํ๋์ง ์กฐํํ๋ SQL๋ฌธ์ ์์ฑํด์ฃผ์ธ์.
์ด๋ ๊ฒฐ๊ณผ๋ ์๊ฐ๋ ์์ผ๋ก ์ ๋ ฌํด์ผ ํฉ๋๋ค.
with recursive timetable as (
select 0 as hour
union all
select hour+1 from timetable
where hour<23
)
select t.hour as hour, count(o.animal_id) as count
from animal_outs o right join timetable t on hour(o.datetime) = t.hour
group by t.hour
order by hour
์ฒ์์๋ group by ํด๋๊ณ ์ ํ๋ฆฐ๊ฑด์ง ์์ํด์ ํ์ฐธ ๋ดค๋ค
์๊ณ ๋ณด๋ ๋ฐ์ดํฐ์ ์๋ ์๊ฐ๋ (์์ ๋ฐ์ดํฐ์์๋ 6์ ๋ฑ..)๋ ๋ณด์ฌ์ค์ผํ๋ ์ํฉ
with๋ฅผ ์ด์ฉํ ์๋ธ์ฟผ๋ฆฌ๋ฅผ ํ์ฉํ์๋ค
recursive๋ฅผ ์ด์ฉํ์ฌ 0๋ถํฐ 24๊น์ง๋ฅผ hour ๊ฐ์ผ๋ก ๊ฐ์ง๋ timetable ์ ๋ง๋ค์ด์ฃผ์๊ณ
์ด๋ฅผ outer join (์ฌ๊ธฐ์ right join)์ ํ์ฉํ์ฌ ๊ฒฐํฉ์์ผ์ฃผ์๋ค.
๊ทธ๋ฆฌ๊ณ ์๊ฐ๋ฐ๋ผ group by ํด์ count ํด์ฃผ๋ฉด ๋
order by๋ ์ํด์ค๋ ๋ฌด๋ฐฉํ๊ธด ํ๋ค