๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป Computer Science/๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

[๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค] SQL GROUP BY & HAVING & ORDER BY ์ด๋ž€? (์˜ˆ์ œ ํฌํ•จ)

by Jay Din 2024. 3. 12.
728x90
๋ฐ˜์‘ํ˜•

GROUP BY, HAVING, ORDER BY๋Š” SQL์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ง‘๊ณ„ํ•˜๊ณ  ์ •๋ ฌํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋˜๋Š” ์ค‘์š”ํ•œ ๊ตฌ๋ฌธ์ž…๋‹ˆ๋‹ค.

๊ฐ๊ฐ์˜ ์—ญํ• ๊ณผ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์„ค๋ช…ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์ •๋ฆฌ ์š”์•ฝ

์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ๋ฌธ๋“ค์„ ์กฐํ•ฉํ•˜์—ฌ SQL ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์›ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ทธ๋ฃนํ™”, ํ•„ํ„ฐ๋ง, ์ •๋ ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

GROUP BY ํŠน์ • ์—ด์˜ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ทธ๋ฃนํ™”ํ•จ
HAVING GROUP BY๋กœ ๊ทธ๋ฃนํ™”๋œ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ์ง€์ •ํ•จ
ORDER BY ๊ฒฐ๊ณผ๋ฅผ ์ •๋ ฌํ•จ

 

GROUP BY

GROUP BY ๊ตฌ๋ฌธ์€ ํŠน์ • ์—ด์˜ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ทธ๋ฃนํ™”ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

์ด๋ฅผ ํ†ตํ•ด ๊ทธ๋ฃน ๋‹จ์œ„๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ง‘๊ณ„ํ•˜๊ณ  ๋ถ„๋ฅ˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์˜ˆ์ œ

ํ•™์ƒ๋“ค์˜ ์„ฑ์  ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋Š” ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค.

ํ•™์ƒ ์ด๋ฆ„ ๊ณผ๋ชฉ ์„ฑ์ •
Alice Math 85
Bob Math 90
Alice Science 88
Bob Science 92

 

์ด์ œ ๊ฐ ํ•™์ƒ๋ณ„๋กœ ์„ฑ์ ์„ ํ‰๊ท  ๋‚ด๋ ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด GROUP BY๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

SELECT ํ•™์ƒ ์ด๋ฆ„, AVG(์„ฑ์ ) AS ํ‰๊ท ์„ฑ์ 
FROM ์„ฑ์ ํ…Œ์ด๋ธ”
GROUP BY ํ•™์ƒ ์ด๋ฆ„;

 

๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

ํ•™์ƒ ์ด๋ฆ„ ํ‰๊ท  ์„ฑ์ 
Alice 86.5
Bob 91

 

HAVING

HAVING ๊ตฌ๋ฌธ์€ GROUP BY๋กœ ๊ทธ๋ฃนํ™”๋œ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ์ง€์ •ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

WHERE ๊ตฌ๋ฌธ์€ ๊ฐœ๋ณ„ ํ–‰์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ์ง€์ •ํ•˜๋Š” ๋ฐ˜๋ฉด, HAVING์€ ๊ทธ๋ฃน์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.

 

์˜ˆ์ œ

์œ„์˜ GROUP BY ์„ค๋ช… ์˜ˆ์ œ์—์„œ, ๋งŒ์•ฝ ํ‰๊ท  ์„ฑ์ ์ด 90๋ณด๋‹ค ๋†’์€ ํ•™์ƒ๋“ค๋งŒ ์„ ํƒํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด HAVING์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

SELECT ํ•™์ƒ ์ด๋ฆ„, AVG(์„ฑ์ ) AS ํ‰๊ท ์„ฑ์ 
FROM ์„ฑ์ ํ…Œ์ด๋ธ”
GROUP BY ํ•™์ƒ ์ด๋ฆ„
HAVING AVG(์„ฑ์ ) > 90;

 

๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

ํ•™์ƒ ์ด๋ฆ„ ํ‰๊ท  ์„ฑ์ 
Bob 91

 

ORDER BY

ORDER BY ๊ตฌ๋ฌธ์€ ๊ฒฐ๊ณผ๋ฅผ ์ •๋ ฌํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

๊ธฐ๋ณธ์ ์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์ง€๋งŒ, DESC ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์˜ˆ์ œ

์˜ˆ๋ฅผ ๋“ค์–ด, ์œ„์˜ ์˜ˆ์ œ์—์„œ ํ•™์ƒ๋“ค์„ ํ‰๊ท  ์„ฑ์ ์— ๋”ฐ๋ผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ORDER BY๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

SELECT ํ•™์ƒ ์ด๋ฆ„, AVG(์„ฑ์ ) AS ํ‰๊ท ์„ฑ์ 
FROM ์„ฑ์ ํ…Œ์ด๋ธ”
GROUP BY ํ•™์ƒ ์ด๋ฆ„
ORDER BY AVG(์„ฑ์ ) DESC;

 

๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

ํ•™์ƒ ์ด๋ฆ„ ํ‰๊ท  ์„ฑ์ 
Bob 91
Alice 86.5

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•