๐Ÿ’ SQL/Group By

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ์ฆ๊ฒจ์ฐพ๊ธฐ๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ์‹๋‹น ์ •๋ณด ์ถœ๋ ฅํ•˜๊ธฐ

์„ ๋‹ฌ 2023. 5. 22. 23:32
๋ฐ˜์‘ํ˜•

https://school.programmers.co.kr/learn/courses/30/lessons/131123

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

์ฒ˜์Œ์—๋Š” ๋ณ„ ์ƒ๊ฐ์—†์ด ์•„์ฃผ ์‰ฝ๊ฒŒ ์ฟผ๋ฆฌ๋ฅผ ์งฐ๋Š”๋ฐ

    SELECT FOOD_TYPE, REST_ID, REST_NAME, max(FAVORITES) as FAVORITES
    from REST_INFO
    group by FOOD_TYPE

ํ‹€๋ ธ๋‹ค.

 

์•Œ๊ณ ๋ณด๋‹ˆ ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด FOOD_TYPE ์ข…๋ฅ˜๋ณ„๋กœ ๊ฐ€์žฅ FAVORITES๊ฐ€ ํฐ FOOD_TYPE๊ณผ FAVORITES ๊ฐ’์€ ๋ฐ˜ํ™˜ํ•ด์ฃผ์ง€๋งŒ ๊ทธ์— ํ•ด๋‹นํ•˜๋Š” REST_ID๋‚˜ REST_NAME์„ ๋Œ€์‘์‹œ์ผœ์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ์ง€ ์•Š๋Š”๊ฒƒ์ด ์›์ธ์ด์˜€๋‹ค.

 

์‹ค์ œ๋กœ ์ € ์ฟผ๋ฆฌ๋กœ ์˜ˆ์ œ๋ฅผ ๋Œ๋ ค๋ณด๋ฉด ์ผ์‹์— ์Šค์‹œ์‚ฌ๋ฌด์‹œ? (์•„์ด๋”” 4๋ฒˆ)์ด ๋‚˜์™€์•ผํ•˜๋Š”๋ฐ ๋‹ค๋ฅธ ์‹๋‹น์ด ๋‚˜์˜ค๋Š”๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์•„๋ฌดํŠผ ๊ทธ๋ฆฌํ•˜์—ฌ ์œ„ ์ฟผ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ตœ๋Œ€ FAVORITES์™€ FOOD_TYPE์„ ๋ฐ˜ํ™˜ํ•œ ๋’ค์—, ์ด ๋ฐ˜ํ™˜ํ•œ ๊ฐ’๊ณผ ์ผ์น˜ํ•˜๋Š” ํ–‰์„ REST_INFO์—์„œ ๋‹ค์‹œ ์ฐพ์•„์„œ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์ดํ•˜์˜€๋‹ค.

 

-- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
select FOOD_TYPE, REST_ID, REST_NAME, FAVORITES
from REST_INFO
where (FOOD_TYPE, FAVORITES) in (
    SELECT FOOD_TYPE, max(FAVORITES) as FAVORITES
    from REST_INFO
    group by FOOD_TYPE
)
order by FOOD_TYPE desc
๋ฐ˜์‘ํ˜•