๐Ÿ•—[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ(2)

๋ฌธ์ œ ์„ค๋ช…

ANIMAL_OUTS ํ…Œ์ด๋ธ”์€ ๋™๋ฌผ ๋ณดํ˜ธ์†Œ์—์„œ ์ž…์–‘ ๋ณด๋‚ธ ๋™๋ฌผ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค. ANIMAL_OUTS ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, ANIMAL_ID, ANIMAL_TYPE, DATETIME, NAME, SEX_UPON_OUTCOME๋Š” ๊ฐ๊ฐ ๋™๋ฌผ์˜ ์•„์ด๋””, ์ƒ๋ฌผ ์ข…, ์ž…์–‘์ผ, ์ด๋ฆ„, ์„ฑ๋ณ„ ๋ฐ ์ค‘์„ฑํ™” ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

๋ณดํ˜ธ์†Œ์—์„œ๋Š” ๋ช‡ ์‹œ์— ์ž…์–‘์ด ๊ฐ€์žฅ ํ™œ๋ฐœํ•˜๊ฒŒ ์ผ์–ด๋‚˜๋Š”์ง€ ์•Œ์•„๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค. 0์‹œ๋ถ€ํ„ฐ 23์‹œ๊นŒ์ง€, ๊ฐ ์‹œ๊ฐ„๋Œ€๋ณ„๋กœ ์ž…์–‘์ด ๋ช‡ ๊ฑด์ด๋‚˜ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์กฐํšŒํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. ์ด๋•Œ ๊ฒฐ๊ณผ๋Š” ์‹œ๊ฐ„๋Œ€ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ

SQL๋ฌธ์„ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‚˜์™€์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋‚˜์˜ ํ’€์ด

-- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
WITH RECURSIVE BASE AS (
    SELECT 0 AS HOUR
    UNION ALL
    SELECT HOUR+1 FROM BASE 
    WHERE HOUR < 23
)

SELECT HOUR AS HOUR, COUNT(ANIMAL_ID) AS COUNT FROM BASE LEFT JOIN ANIMAL_OUTS ON BASE.HOUR = HOUR(ANIMAL_OUTS.DATETIME) GROUP BY HOUR ORDER BY HOUR;

WITH RECURSIVE ๊ฐ€ ์ค‘์š”ํ•œ๋ฐ, ํ•ด๋‹น ๋ฌธ๋ฒ•์€ ์žฌ๊ท€๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

์ฆ‰ ๊ฐ’์ด 0์ธ ์ปฌ๋Ÿผ๊ณผ 0 ~ 22 ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉฐ ์ปฌ๋Ÿผ ์ด๋ฆ„์„ n+1 ๋กœ ๊ฐ–๋Š” ํ…Œ์ด๋ธ”์„ ์ƒ์„ฑํ•œ๋‹ค.

๊ทธ ํ›„ LEFT JOIN์œผ๋กœ ์กฐํšŒํ•˜๋ฉด ๋

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ