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

ruriruriya

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

๐Ÿ›ข๏ธDB/MySQL

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

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 12. 2. 11:56
๋ฐ˜์‘ํ˜•

 

MySQL์˜ GROUP BY์™€ HAVING์„ ํ•จ๊ป˜
์‚ฌ์šฉํ•˜์—ฌ ์กฐ๊ฑด์— ๋งž๋Š” ๊ทธ๋ฃน์„ ํ•„ํ„ฐ๋งํ•˜๋Š” ๋ฐฉ๋ฒ•

 

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

์˜ˆ๋ฅผ ๋“ค์–ด, ํ•™์ƒ ํ…Œ์ด๋ธ”์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.. ์ด ํ…Œ์ด๋ธ”์—๋Š” ํ•™์ƒ ์ด๋ฆ„๊ณผ ๊ฐ ํ•™์ƒ์˜ ์„ฑ์ ์ด ์žˆ๋‹ค.
(ํ‰๊ท  ๊ฐ’์„ ๋‚ด๊ธฐ ์œ„ํ•ด ์ ์ˆ˜๋ฅผ ํ•œ๋ฒˆ ๋” ์ถ”๊ฐ€ํ–ˆ๋‹ค...(๋‘๋ฒˆ ์งธ insert ๋ฌธ))

INSERT INTO students (student_name, grade)
VALUES
    ('Alice', 90),
    ('Bob', 85),
    ('Charlie', 75),
    ('David', 95),
    ('Emma', 88),
    ('Frank', 82),
    ('Grace', 79),
    ('Henry', 91),
    ('Isabella', 87),
    ('Jack', 93);
    
INSERT INTO students (student_name, grade)
VALUES
    ('Alice', 70),
    ('Bob', 95),
    ('Charlie', 65),
    ('David', 85),
    ('Emma', 80),
    ('Frank', 89),
    ('Grace', 95),
    ('Henry', 71),
    ('Isabella', 77),
    ('Jack', 43);

๋จผ์ € ํ•™์ƒ๋“ค๋ณ„๋กœ ๊ทธ๋ฃนํ™”๋ฅผ ํ•˜์—ฌ
๊ทธ๋“ค์˜ ํ‰๊ท  ๊ฐ’์„ ๋‚ด์–ด ๋ณธ๋‹ค.

SELECT student_name, AVG(grade) as average_grade
FROM students
GROUP BY student_name;

SELECT student_name, AVG(grade) as average_grade
FROM students
GROUP BY student_name
HAVING AVG(grade) > 85;

์œ„์˜ ์ฟผ๋ฆฌ๋Š” ๊ฐ ํ•™์ƒ์˜ ํ‰๊ท  ์„ฑ์ ์„ ๊ณ„์‚ฐํ•˜๊ณ , ๊ทธ๋ฃนํ™”๋œ ๊ฒฐ๊ณผ์—์„œ ํ‰๊ท  ์„ฑ์ ์ด 85๋ณด๋‹ค ํฐ ํ•™์ƒ๋“ค๋งŒ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

์ด ์ฟผ๋ฆฌ์—์„œ ์ค‘์š”ํ•œ ์ ์€
GROUP BY๋กœ ๊ทธ๋ฃนํ™”๋œ ํ›„์—
HAVING ์ ˆ์—์„œ ํ‰๊ท  ์„ฑ์ ์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ์ ์šฉํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

HAVING ์ ˆ์€ WHERE ์ ˆ๊ณผ ์œ ์‚ฌํ•˜์ง€๋งŒ,
WHERE์€ ํ–‰ ๋‹จ์œ„๋กœ ์กฐ๊ฑด์„ ์ ์šฉํ•˜๋Š” ๋ฐ˜๋ฉด,
HAVING์€ GROUP BY๋กœ ๊ทธ๋ฃนํ™”๋œ ๊ฒฐ๊ณผ์— ์กฐ๊ฑด์„ ์ ์šฉํ•œ๋‹ค.

์ด์ฒ˜๋Ÿผ HAVING์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ทธ๋ฃนํ™”๋œ ๋ฐ์ดํ„ฐ์—์„œ ํŠน์ • ์กฐ๊ฑด์„ ๊ฐ€์ง„ ๊ทธ๋ฃน์„ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

๋ฐ˜์‘ํ˜•