Search

์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ(1)

์ƒ์„ฑ์ผ
2022/03/03 18:02
ํ”Œ๋žซํผ
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค
ํƒœ๊ทธ
GROUP BY
level
2
๋ถ„๋ฅ˜
๊ทธ๋Ÿญ์ €๋Ÿญ ํ•ด๊ฒฐ
๋งํฌ

Problem

๋ฌธ์ œ ์„ค๋ช…

ANIMAL_OUTSย ํ…Œ์ด๋ธ”์€ ๋™๋ฌผ ๋ณดํ˜ธ์†Œ์—์„œ ์ž…์–‘ ๋ณด๋‚ธ ๋™๋ฌผ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค.ย ANIMAL_OUTSย ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ,ย ANIMAL_ID,ย ANIMAL_TYPE,ย DATETIME,ย NAME,ย SEX_UPON_OUTCOME๋Š” ๊ฐ๊ฐ ๋™๋ฌผ์˜ ์•„์ด๋””, ์ƒ๋ฌผ ์ข…, ์ž…์–‘์ผ, ์ด๋ฆ„, ์„ฑ๋ณ„ ๋ฐ ์ค‘์„ฑํ™” ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.
Search
NAME
TYPE
NULLABLE
VARCHAR(N)
FALSE
DATETIME
FALSE
VARCHAR(N)
TRUE
VARCHAR(N)
FALSE
๋ณดํ˜ธ์†Œ์—์„œ๋Š” ๋ช‡ ์‹œ์— ์ž…์–‘์ด ๊ฐ€์žฅ ํ™œ๋ฐœํ•˜๊ฒŒ ์ผ์–ด๋‚˜๋Š”์ง€ ์•Œ์•„๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค. 09:00๋ถ€ํ„ฐ 19:59๊นŒ์ง€, ๊ฐ ์‹œ๊ฐ„๋Œ€๋ณ„๋กœ ์ž…์–‘์ด ๋ช‡ ๊ฑด์ด๋‚˜ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์กฐํšŒํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. ์ด๋•Œ ๊ฒฐ๊ณผ๋Š” ์‹œ๊ฐ„๋Œ€ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ

SQL๋ฌธ์„ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‚˜์™€์•ผ ํ•ฉ๋‹ˆ๋‹ค.
Search
HOUR
COUNT
9
1
10
2
11
13
12
10
13
14
14
9
15
7
16
10
17
12
18
16
19
2

Code

ย #1

Idea

ย Code

SELECT HOUR(DATETIME) AS HOUR, COUNT(ANIMAL_ID) AS COUNT FROM ANIMAL_OUTS GROUP BY HOUR(DATETIME) HAVING HOUR BETWEEN 9 AND 20 ORDER BY HOUR(DATETIME)
SQL
๋ณต์‚ฌ

Solution

Commentary

having ์ ˆ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์—ด ์ด๋ฆ„์€ ์ˆœ์ˆ˜ํ•œ ์—ด์ด๋ฆ„์ด์–ด์•ผ ํ•œ๋‹ค. (ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋ณ€ํ˜•์„ ๊ฐ€ํ•˜๋ฉด ์•ˆ ๋จ. alias ๋Š” ๋จ)
-- ์—๋Ÿฌ SELECT HOUR(DATETIME) AS HOUR, COUNT(ANIMAL_ID) AS COUNT FROM ANIMAL_OUTS GROUP BY HOUR(DATETIME) HAVING HOUR(DATETIME) BETWEEN 9 AND 20 -- ๋ถ€๋“ฑํ˜ธ ์ด์šฉํ•˜๋Š” ๋ฐฉ์‹๋„ ๋‹น์—ฐํžˆ ๊ฐ€๋Šฅ ORDER BY HOUR(DATETIME)
SQL
๋ณต์‚ฌ
HOUR(DATETIME) ์ฒ˜๋Ÿผ ํ•จ์ˆ˜๋ฅผ ๋ฎ์–ด์”Œ์šด ์—ด์€ having ์ ˆ์—์„œ ์‚ฌ์šฉ๋ชปํ•œ๋‹ค.