๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - GROUP BY, HAVING ์‚ฌ์šฉ ๋ฐฉ๋ฒ• ๋ณธ๋ฌธ

๐Ÿ›ข๏ธDB/MySQL

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - GROUP BY, HAVING ์‚ฌ์šฉ ๋ฐฉ๋ฒ•

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 11. 30. 13:21
๋ฐ˜์‘ํ˜•

GROUP BY ๋ฐ HAVING์€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ทธ๋ฃนํ™”ํ•˜๊ณ  ์กฐ๊ฑด์— ๋”ฐ๋ผ ํ•„ํ„ฐ๋งํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋˜๋Š” ์ค‘์š”ํ•œ ํ‚ค์›Œ๋“œ์ด๋‹ค.

์‚ฌ์šฉํ•  ํ…Œ์ด๋ธ”(books)

 

GROUP BY

์นดํ…Œ๊ณ ๋ฆฌ์ปฌ ๋ฐ์ดํ„ฐ์˜ ๊ฒฝ์šฐ  ~ ๋ณ„๋กœ ๋ฌถ์–ด์„œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

ํŠน์ • ์—ด์˜ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ทธ๋ฃนํ™”ํ•˜๊ณ  ์ดํ›„ ์ง‘๊ณ„ ํ•จ์ˆ˜(COUNT(), SUM(), AVG(), MAX(), MIN() ๋“ฑ)์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜์—ฌ ๊ทธ๋ฃน๋ณ„๋กœ ์š”์•ฝ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.

author_lname ๋ณ„๋กœ, ๋ช‡ ๊ถŒ์˜ ์ฑ…์„ ์ผ๋Š”์ง€ ๊ถŒ์ˆ˜๋ฅผ ๋ณด์—ฌ์ฃผ์„ธ์š”.

select author_lname, count(*) as book_count
from books
group by author_lname;

๋…„๋„๋ณ„๋กœ ๊ฐ๊ฐ ๋ช‡ ๊ถŒ์˜ ์ฑ…์ด ์ถœ๊ฐ„๋˜์—ˆ๋Š”์ง€
๋…„๋„์™€ ์ฑ…์˜ ๊ฐฏ์ˆ˜๋ฅผ ๋ณด์—ฌ์ฃผ์„ธ์š”.

select released_year, count(*) as cnt
from books
group by released_year
order by cnt desc;

HAVING

ํ…Œ์ด๋ธ”์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ปฌ๋Ÿผ์— ๋Œ€ํ•œ ์กฐ๊ฑด์ผ ๊ฒฝ์šฐ
ํŠนํžˆ, group by!!!! ์ผ๋•Œ ์กฐ๊ฑด์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•

๋…„๋„๋ณ„ ์žฌ๊ณ ์˜ ํ‰๊ท ๊ฐ’์ด 70๋ณด๋‹ค ํฐ ์ฑ…๋“ค์˜, ๋…„๋„์™€ ํ‰๊ท  ๊ฐ’์„ ๋ณด์—ฌ์ฃผ์„ธ์š”.

select released_year , avg(stock_quantity) as avg_stock
from books
group by released_year
having avg_stock >= 70;

์ถœํŒ๋…„๋„ 2000๋…„ ์ด์ƒ์ธ ๋ฐ์ดํ„ฐ์—์„œ,
๋…„๋„๋ณ„ ์žฌ๊ณ ์ˆ˜๋Ÿ‰์˜ ํ‰๊ท ๊ฐ’์ด 70๋ณด๋‹ค ํฐ
์ฑ…๋“ค์˜, ๋…„๋„์™€ ํ‰๊ท ๊ฐ’์„ ๋ณด์—ฌ์ฃผ์„ธ์š”.

select title, released_year, avg(stock_quantity) as avg_stock
from books
where released_year >= 2000
group by released_year
having avg_stock >=70;

 

GROUP BY์™€ HAVING์„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋ฉด ๊ทธ๋ฃนํ™”๋œ ๋ฐ์ดํ„ฐ์—์„œ ์›ํ•˜๋Š” ์กฐ๊ฑด์„ ๊ฐ€์ง„ ๊ทธ๋ฃน์„ ์„ ํƒํ•˜๊ฑฐ๋‚˜ ํ•„ํ„ฐ๋งํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ํŠน์ • ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ง‘๊ณ„๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”์ถœํ•˜๊ฑฐ๋‚˜, ๊ทธ๋ฃน ๋‹จ์œ„๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถ„์„ํ•˜๋Š” ๋ฐ ์œ ์šฉํ•˜๊ฒŒ ํ™œ์šฉ๋œ๋‹ค.

๋ฐ˜์‘ํ˜•