๐Ÿ’ SQL/Group By

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] SQL ๊ณ ๋“์  Kit: ๊ฐ€๊ฒฉ๋Œ€ ๋ณ„ ์ƒํ’ˆ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ

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

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

 

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

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

programmers.co.kr

 

 

์ฒ˜์Œ์—๋Š” ํ’€์ด2๋กœ ํ’€์—ˆ์œผ๋‚˜ ๋„ˆ๋ฌด ๋…ธ๊ฐ€๋‹ค๋ผ๋Š” ์ƒ๊ฐ์— ํ’€์ด1๋กœ ํ’€์—ˆ๋‹ค

 

ํ’€์ด1

๋‚ด๋ฆผ ์—ฐ์‚ฐ (floor)์„ ์ด์šฉํ•œ ํ’€์ด

-- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
SELECT floor(PRICE/10000)*10000 as PRICE_GROUP, count(*) as PRODUCTS
from PRODUCT
group by PRICE_GROUP
order by PRICE_GROUP asc

 

ํ’€์ด2

case when then ๊ณผ between ์„ ์ด์šฉํ•œ ํ’€์ด

-- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
SELECT (case when PRICE between 0 and 9999 then 0
        when PRICE between 10000 and 19999 then 10000
        when PRICE between 20000 and 29999 then 20000
        when PRICE between 30000 and 39999 then 30000
        when PRICE between 40000 and 49999 then 40000
        when PRICE between 50000 and 59999 then 50000
        when PRICE between 60000 and 69999 then 60000
        when PRICE between 70000 and 79999 then 70000
        when PRICE between 80000 and 89999 then 80000
        when PRICE between 90000 and 99999 then 90000
        end) as PRICE_GROUP,
        count(*) as PRODUCTS
from PRODUCT
group by PRICE_GROUP
order by PRICE_GROUP asc
๋ฐ˜์‘ํ˜•