ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต

๊ธฐ์ดˆ๋ถ€ํ„ฐ ์ฐจ๊ทผ์ฐจ๊ทผ, ์ง์ ‘ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด ๋ณด์„ธ์š”.

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ํ•„๋“œ์˜ ๊ฐ’ ๋ณ„๋กœ ๋ฌถ์–ด์„œ ์กฐํšŒํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒฝ์šฐ `GROUP BY`๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. ๊ฐ ๋ฌธ์ œ๋“ค์€ `GROUP BY`๋ฅผ ํ†ตํ•ด ์กฐํšŒํ•˜๊ณ ์ž ํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•˜๋Š” ๋ฌธ์ œ๋“ค์ด๋‹ค.

 

์ฝ”๋“œ

๊ณ ์–‘์ด์™€ ๊ฐœ๋Š” ๋ช‡ ๋งˆ๋ฆฌ ์žˆ์„๊นŒ

SELECT ANIMAL_TYPE, COUNT(ANIMAL_TYPE) AS COUNT
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE

 `GROUP BY`๋ฅผ ํ†ตํ•ด `ANIMAL_TYPE`์œผ๋กœ ๊ทธ๋ฃน์„ ๋งŒ๋“ค๋ฉด, ๋™๋ฌผ ๋ณ„๋กœ ์นด์šดํŠธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๋™๋ช… ๋™๋ฌผ ์ˆ˜ ์ฐพ๊ธฐ

SELECT NAME, Count(*) AS COUNT
FROM ANIMAL_INS
WHERE NOT NAME IS NULL
GROUP BY NAME HAVING COUNT > 1
ORDER BY NAME

 `GROUP BY`๋ฅผ ํ†ตํ•ด `NAME`์œผ๋กœ ๋ฌถ๊ณ , `HAVING`์„ ํ†ตํ•ด ์นด์šดํŠธ๊ฐ€ 1 ์ด์ƒ์ธ ๊ฒฝ์šฐ๊ฐ€ ๋™๋ช… ๋™๋ฌผ์˜ ์ˆ˜์ด๋‹ค.

 

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

SELECT HOUR(DATETIME) AS HOUR, COUNT(DATETIME) AS COUNT
FROM ANIMAL_OUTS
WHERE 9 <= HOUR(DATETIME) AND HOUR(DATETIME) < 20
GROUP BY HOUR(DATETIME)
ORDER BY HOUR(DATETIME)

 `HOUR`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„๋งŒ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค. ์—ฌ๊ธฐ์— `WHERE`์™€ `GROUP BY`๋ฅผ ํ†ตํ•ด ์›ํ•˜๋Š” ์กฐ๊ฑด์„ ์„ ํƒํ•˜๋ฉด ๋ฌธ์ œ์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค.

 

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

SET @hour = -1; 
SELECT (@hour := @hour + 1) AS HOUR, ( 
    SELECT COUNT(DATETIME)      
    FROM ANIMAL_OUTS 
    WHERE HOUR(DATETIME) = @hour 
) AS COUNT
FROM ANIMAL_OUTS 
WHERE @hour < 23

 ์ด์™€ ๊ฐ™์ด ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด, `UNION`, `SELECT`๋ฅผ ๊ณ„์† ๋ฐ˜๋ณตํ•ด์„œ ์จ์•ผ ํ•œ๋‹ค. ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ์ฐพ์•„๋ณด๋‹ˆ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž‘์„ฑํ•˜๋ฉด ๊น”๋”ํ•˜๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€