GROUP BY

๋ฐ์ดํ„ฐ์—์„œ ์˜๋ฏธ๋ฅผ ์ฐพ๊ณ  ์‹ถ์œผ๋ฉด

์ „์ฒด๋ฅผ ํ†ต๊ณ„๋‚ด๋Š” ๊ฒƒ ๋ณด๋‹ค ํŠน์ • ๊ทธ๋ฃน์„ ๋ฝ‘์•„์„œ ํ†ต๊ณ„๋ฅผ ๋‚ด๋Š”๊ฒŒ ํ›จ์”ฌ ์˜๋ฏธ์ฐพ๊ธฐ ์‰ฝ๋‹ค๊ณ  ํ–ˆ์Šต๋‹ˆ๋‹ค.

ํŠน์ • ๊ทธ๋ฃน์„ ๋ฝ‘๊ณ  ์‹ถ์œผ๋ฉด WHERE ์จ์„œ ํ•„ํ„ฐ๋งํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

SELECT AVG(์‚ฌ์šฉ๊ธˆ์•ก) FROM CARD WHERE ๊ณ ๊ฐ๋“ฑ๊ธ‰ = 'vip';
SELECT AVG(์‚ฌ์šฉ๊ธˆ์•ก) FROM CARD WHERE ๊ณ ๊ฐ๋“ฑ๊ธ‰ = 'ํŒจ๋ฐ€๋ฆฌ';
SELECT AVG(์‚ฌ์šฉ๊ธˆ์•ก) FROM CARD WHERE ๊ณ ๊ฐ๋“ฑ๊ธ‰ = '๋กœ์—ด';

๊ทธ๋ฃน ๋ฝ‘์„๊ฒŒ ๋งŽ๋‹ค๋ฉด GROUP BY ๋ฌธ๋ฒ• ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

GROUP BY

SELECT ๊ณ ๊ฐ๋“ฑ๊ธ‰ FROM card 
GROUP BY ๊ณ ๊ฐ๋“ฑ๊ธ‰ 


SELECT ๊ณ ๊ฐ๋“ฑ๊ธ‰, AVG(์‚ฌ์šฉ๊ธˆ์•ก) FROM card 
GROUP BY ๊ณ ๊ฐ๋“ฑ๊ธ‰ 

GROUP BY๋Š” ์ „์— ํ–ˆ๋˜ MIN MAX COUNT SUM AVG ํ•จ์ˆ˜์™€ ํ•จ๊ป˜ ์ด์šฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งค์šฐ ๋งŽ์Šต๋‹ˆ๋‹ค.

๊ทธ๋Ÿผ ๊ฐ๊ฐ์˜ ์นดํ…Œ๊ณ ๋ฆฌ๋งˆ๋‹ค MIN MAX COUNT SUM AVG ๊ฐ’์„ ์ถœ๋ ฅํ•ด๋ณผ ์ˆ˜ ์žˆ์Œ

SELECT ๊ณ ๊ฐ๋“ฑ๊ธ‰, COUNT(๊ณ ๊ฐ๋ช…) FROM card 
GROUP BY ๊ณ ๊ฐ๋“ฑ๊ธ‰ 

COUNT(๊ณ ๊ฐ๋ช…) ์ปฌ๋Ÿผ์„ ์ถ”๊ฐ€ํ•˜๋ฉด

๊ฐ ์นดํ…Œ๊ณ ๋ฆฌ๋งˆ๋‹ค COUNT(๊ณ ๊ฐ๋ช…)์„ ์ถœ๋ ฅํ•ด์ค๋‹ˆ๋‹ค.

GROUP BY๋Š” category column์— ์ฃผ๋กœ ์‚ฌ์šฉํ•จ

PRODUCT์—์„œ๋Š” ์นดํ…Œ๊ณ ๋ฆฌ ์ปฌ๋Ÿผ, CARD ํ…Œ์ด๋ธ”์—์„œ๋Š” ๊ณ ๊ฐ๋“ฑ๊ธ‰ ์ปฌ๋Ÿผ

GROUP BY ํ•œ ๊ฒฐ๊ณผ๋„ ํ•„ํ„ฐ๋ง ๊ฐ€๋Šฅ

GROUP BY๋กœ ๊ทธ๋ฃน์ง€์–ด์„œ ์ถœ๋ ฅํ•œ ๊ฒƒ๋„ ๋„ˆ๋ฌด ํ–‰์ด ๋งŽ์œผ๋ฉด ํ•„ํ„ฐ๋งํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ

๋’ค์— HAVING ์กฐ๊ฑด๋ฌธ ์“ฐ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

GROUP BY ๋’ค์—๋งŒ ๋ถ™์ผ ์ˆ˜ ์žˆ๋Š” ํŠน๋ณ„ํ•œ ์กฐ๊ฑด๋ฌธ์ž…๋‹ˆ๋‹ค.

SELECT ๊ณ ๊ฐ๋“ฑ๊ธ‰, COUNT(๊ณ ๊ฐ๋ช…) FROM card 
GROUP BY ๊ณ ๊ฐ๋“ฑ๊ธ‰ 
HAVING ๊ณ ๊ฐ๋“ฑ๊ธ‰ = 'vip' 

HAVING vs WHERE

HAVING์€ ์šฉ๋„๊ฐ€ WHERE๊ณผ ๋น„์Šทํ•ฉ๋‹ˆ๋‹ค. ๋‘˜ ๋‹ค ์กฐ๊ฑด์‹ ์ž…๋ ฅํ•˜๋Š” ๋ฌธ๋ฒ•์ž…๋‹ˆ๋‹ค.

-HAVING์€ GROUP BY ๊ฒฐ๊ณผ๋ฅผ ํ•„ํ„ฐ๋งํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์”๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ GROUP BY ๋’ค์—๋งŒ ๋ถ™์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

- WHERE๋Š” ํ…Œ์ด๋ธ” ์ „์ฒด ๋ฐ์ดํ„ฐ ์ถœ๋ ฅ์‹œ ํ•„ํ„ฐ๋งํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์“ฐ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ SELECT FROM ๋’ค์—๋งŒ ๋ถ™์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

SELECT / FROM / WHERE / GROUP BY / HAVING / ORDER BY ์ˆœ์œผ๋กœ ์ž‘์„ฑํ•œ๋‹ค๊ณ  ์™ธ์šฐ๋ผ๊ณ  ์‹œํ‚ค๋Š”๋ฐ

๊ทผ๋ฐ ๊ฐ๊ฐ ๋ฌธ๋ฒ•์˜ ์šฉ๋„๋งŒ ์ž˜ ๊ธฐ์–ตํ•ด๋‘๋ฉด ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ˆœ์„œ ์™ธ์šฐ๊ณ  ๊ทธ๋Ÿด ํ•„์š”์—†์Šต๋‹ˆ๋‹ค.

๋ฌธ๋ฒ•์˜ ์šฉ๋„๋งŒ ์ž˜ ๊ธฐ์–ตํ•ด๋‘ก์‹œ๋‹ค.

Q1. ์œ„ ์‚ฌ์ง„์ฒ˜๋Ÿผ CARD ํ…Œ์ด๋ธ”์—์„œ ๊ฐ ์—ฐ์ฒดํšŸ์ˆ˜๋งˆ๋‹ค ๋ช‡๋ช…์ด ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•ด๋ด…์‹œ๋‹ค.

Q2. Q1์—์„œ ์ถœ๋ ฅํ•œ ๊ฒฐ๊ณผ๊ฐ€ ๋„ˆ๋ฌด ๊ธธ์–ด์„œ '๋ช‡๋ช…' ์ปฌ๋Ÿผ์˜ ๊ฐ’์ด 1๋ช…์ธ ํ–‰์€ ์•ˆ๋ณด์ด๊ฒŒ ํ•„ํ„ฐ๋งํ•ด๋ด…์‹œ๋‹ค.

Q3. ์œ„ ์‚ฌ์ง„์ฒ˜๋Ÿผ card ํ…Œ์ด๋ธ”์—์„œ ํšŒ์›๋“ฑ๊ธ‰๋ณ„๋กœ ์ตœ๋Œ€์‚ฌ์šฉ๊ธˆ์•ก๊ณผ ์ตœ์†Œ์‚ฌ์šฉ๊ธˆ์•ก์ด ๋ช‡๋ฐฐ๋‚˜ ์ฐจ์ด๋‚˜๋Š”์ง€ ๊ตฌํ•ด๋ด…์‹œ๋‹ค.

Last updated