PG SQL ๐Ÿ“Œ GROUP BY

imsยท2021๋…„ 2์›” 23์ผ
0

SQL

๋ชฉ๋ก ๋ณด๊ธฐ
9/12

๐Ÿ“Œ GROUP BY ๊ฐœ๋…

๊ฐœ๋…

https://extbrain.tistory.com/56

  • WHERE๋ž‘ HAVING์„ ํ—ท๊น”๋ฆฌ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์€๋ฐ WHERE๋Š” ๊ทธ๋ฃนํ™” ํ•˜๊ธฐ ์ „์ด๊ณ , HAVING์€ ๊ทธ๋ฃนํ™” ํ›„์— ์กฐ๊ฑด์ž…๋‹ˆ๋‹ค.

์œ ํ˜•๋ณ„๋กœ ๊ฐฏ์ˆ˜๋ฅผ ์•Œ๊ณ ์‹ถ์„ ๋•Œ = GROUP BY

ํŠน์ • ์ปฌ๋Ÿผ์„ ๊ทธ๋ฃนํ™” = GROUP BY

ํŠน์ • ์ปฌ๋Ÿผ์„ ๊ทธ๋ฃนํ™”ํ•œ ๊ฒฐ๊ณผ์— ์กฐ๊ฑด์„ ๊ฒ€ = HAVING

์œ„์™€ ๊ฐ™์€ table์ด ์žˆ๋‹ค๊ณ  ํ–ˆ์„ ๋•Œ

group_by ํ•˜๋ฉด name์ด ์ž˜๋ฆผ

์œ„์™€ ๊ฐ™์ด ๊ทธ๋ฃน๋ณ„๋กœ ๋ฌถ์„ ์ˆ˜ ์žˆ๋‹ค.

๐Ÿ“Œ ๊ณ ์–‘์ด์™€ ๊ฐœ ( GROUP BY )

๊ฐœ๋‚˜ ๊ณ ์–‘์ด ์ด๋ฆ„์ด 2๊ฐœ ์ด์ƒ์ธ ๊ฒฝ์šฐ๋งŒ ์ถœ๋ ฅ , ๊ฐœ์™€ ๊ณ ์–‘์ด ์ด๋ฆ„์˜ ๊ฐœ์ˆ˜์„ธ๊ธฐ

๐Ÿ”ฅ Having ํ’€์ด

SELECT name,count(*) AS count FROM animal_ins
GROUP BY name 
HAVING count(name)>=2 
ORDER BY name

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

https://chanhuiseok.github.io/posts/db-6/

์‹œ๊ฐ„๋Œ€(hour) ๋ณ„๋กœ ์ซ™ ์ •๋ ฌ, ๊ฐ ์‹œ๊ฐ„๋Œ€์˜ ์ˆซ์ž ๊ตฌํ•˜๊ธฐ

SELECT HOUR(DATETIME) HOUR, COUNT(DATETIME) COUNT
FROM ANIMAL_OUTS
GROUP BY HOUR(DATETIME)
HAVING HOUR >= 9 and HOUR <= 20
ORDER BY HOUR

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

0~23์‹œ, ๋ชจ๋“  ๊ฐœ์ฒด ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ผ

๐Ÿ”ฅ ์ฒ˜์Œ ์ƒ๊ฐํ–ˆ๋˜ ๊ฒƒ

SELECT HOUR(datetime) HOUR, count(*) COUNT FROM ANIMAL_OUTS
GROUP BY HOUR(datetime)
HAVING HOUR>=0 and HOUR<=23
ORDER BY HOUR

์ด๋Ÿฌ๋ฉด 7์‹œ~19์‹œ์˜ ๊ฐ’ : ๋ฌธ์ œ ์•ˆ์—์„œ 0์ด ์•„๋‹Œ ๊ฐ’๋“ค๋งŒ ๊ฐ€์ ธ์™€์ง„๋‹ค.

https://chanhuiseok.github.io/posts/db-6/

๐Ÿงฟ @์—ฐ์‚ฐ์ž

SET @hour := -1; // => ๋ณ€์ˆ˜์„ ์–ธ
:=  // => ๋Œ€์ž… ์—ฐ์‚ฐ์ž

๐Ÿ”ฅ ๋‹ต

SET @h := -1;

SELECT (@h := @h +1) as HOUR, 
(SELECT count(*) FROM ANIMAL_OUTS WHERE HOUR(DATETIME) = @h) as COUNT
FROM ANIMAL_OUTS
HAVING @h<23
profile
ํ‹ฐ์Šคํ† ๋ฆฌ๋กœ ์ด์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค! https://imsfromseoul.tistory.com/ + https://camel-man-ims.tistory.com/

0๊ฐœ์˜ ๋Œ“๊ธ€