Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

BUILD_SSO

[MySQL] GROUP BY, HAVING, ORDER BY ๋ณธ๋ฌธ

Programming/SQL | MySQL

[MySQL] GROUP BY, HAVING, ORDER BY

sohyeonnn 2023. 5. 2. 17:30

๐Ÿ“ŒGROUP BY

  • ๋ฐ์ดํ„ฐ๋ฅผ ํŠน์ • ์ปฌ๋Ÿผ ๊ธฐ์ค€์œผ๋กœ ๊ทธ๋ฃนํ™” ์‹œํ‚ค๋Š” ๋ช…๋ น์–ด
    ex. ์—ฐ๋ น๋ณ„ ํ‰๊ท  ๋งค์ถœ์•ก → ์—ฐ๋ น๋ณ„๋กœ ๊ทธ๋ฃนํ™”
  • ๊ฐ ๊ทธ๋ฃน์— ๋Œ€ํ•œ ์—ฐ์‚ฐ๊ฒฐ๊ณผ(ํ•ฉ, ํ‰๊ท , ๊ฐฏ์ˆ˜)๋ฅผ ์‚ฐ์ถœํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ง‘๊ณ„ํ•จ์ˆ˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค.
  • GROUP BY ์ ˆ์— ์žˆ๋Š” ์ปฌ๋Ÿผ์€ ๋ฐ˜๋“œ์‹œ SELECT ์ ˆ์—๋„ ์กด์žฌํ•ด์•ผํ•œ๋‹ค.

์˜ˆ์‹œ ์ฝ”๋“œ:

-- ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_๊ณ ์–‘์ด์™€ ๊ฐœ๋Š” ๋ช‡๋งˆ๋ฆฌ ์žˆ์„๊นŒ

SELECT ANIMAL_TYPE, COUNT(ANIMAL_TYPE) AS count
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE

 

*๊ทธ๋ฃน ํ•จ์ˆ˜๋ž€?

ํ•˜๋‚˜ ์ด์ƒ์˜ ํ–‰์„ ๊ทธ๋ฃน์œผ๋กœ ๋ฌถ์–ด ์—ฐ์‚ฐํ•˜๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜์ด๋ฉฐ, GROUP BY๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆ ์ง„ ๊ฐ ๊ทธ๋ฃน์„ ์—ฐ์‚ฐํ•˜๋Š” ์—ญํ• ์„ ํ•œ๋‹ค.
COUNT ํ•จ์ˆ˜๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๊ทธ๋ฃนํ•จ์ˆ˜๋Š” NULL๊ฐ’์„ ์ œ์™ธํ•˜๊ณ  ๊ณ„์‚ฐํ•œ๋‹ค(COUNT๋Š” NULL์„ ํฌํ•จ. ์ฆ‰, ๋ชจ๋“  ์›์†Œ๋ฅผ ์„ธ์–ด์คŒ)
โžก ๊ทธ๋ฃนํ•จ์ˆ˜ ์ข…๋ฅ˜: COUNT, SUM, AVG, MAX, MIN, STDDDEV(ํ‘œ์ค€ํŽธ์ฐจ), VARIANCE(๋ถ„์‚ฐ)

 

๐Ÿ“ŒHAVING

  • GROUP BY ์ ˆ์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ๊ฑธ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๋ช…๋ น์–ด
    → ์ฆ‰, ๊ทธ๋ฃนํ™” ๋œ ๊ฒฐ๊ณผ์— ์กฐ๊ฑด์„ ๊ฑธ์–ด์ฃผ๋Š” ์—ญํ• ์„ ํ•œ๋‹ค.
  • HAVING ๋’ค์—๋Š” SELECT ๊ตฌ๋ฌธ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ‘AS ๋ณ„์นญ’ ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€ํ•˜๋‹ค.

 

*WHERE, HAVING ์ฐจ์ด

์ฒ˜์Œ๋ถ€ํ„ฐ ํ…Œ์ด๋ธ” ์ž์ฒด์— ์กฐ๊ฑด์„ ๊ฑธ๊ณ ์‹ถ๋‹ค๋ฉด → WHERE
๊ทธ๋ฃน๋ณ„๋กœ ๋ฌถ์ธ ์ปฌ๋Ÿฝ์— ์กฐ๊ฑด์„ ๊ฑธ๊ณ ์‹ถ๋‹ค๋ฉด → HAVING

 

๐Ÿ“ŒORDER BY

  • ํ…Œ์ด๋ธ”์„ ํŠน์ • ์ปฌ๋Ÿผ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ ์œ„ํ•œ ๋ช…๋ น์–ด
    → ์ฆ‰, ์ •๋ ฌ์˜ ์—ญํ• ์„ ํ•œ๋‹ค.
  • ์—ฌ๋Ÿฌ๊ฐœ ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
    ex. ORDER BY COL1, COL2, …
  • ๊ธฐ๋ณธ ์„ค์ •์€ ์˜ค๋ฆ„์ฐจ์ˆœ(ASC)์ด๋‹ค.
  • SELECT ์ ˆ์˜ ์ปฌ๋Ÿผ ์ˆœ์„œ๋‚˜ ๋ณ„์นญ(AS ๋ณ„์นญ)์œผ๋กœ๋„ ์ •๋ ฌ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
    ex. ORDER BY 1, 2 ….
Comments