๐Ÿ’ SQL/Group By

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ์ €์ž ๋ณ„ ์นดํ…Œ๊ณ ๋ฆฌ ๋ณ„ ๋งค์ถœ์•ก ์ง‘๊ณ„ํ•˜๊ธฐ

์„ ๋‹ฌ 2023. 6. 28. 23:01
๋ฐ˜์‘ํ˜•

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

 

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

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

programmers.co.kr

 

2022๋…„ 1์›”์˜ ๋„์„œ ํŒ๋งค ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ

์ €์ž ๋ณ„, ์นดํ…Œ๊ณ ๋ฆฌ ๋ณ„

๋งค์ถœ์•ก(TOTAL_SALES = ํŒ๋งค๋Ÿ‰ * ํŒ๋งค๊ฐ€) ์„ ๊ตฌํ•˜์—ฌ,

์ €์ž ID(AUTHOR_ID), ์ €์ž๋ช…(AUTHOR_NAME), ์นดํ…Œ๊ณ ๋ฆฌ(CATEGORY), ๋งค์ถœ์•ก(SALES) ๋ฆฌ์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
๊ฒฐ๊ณผ๋Š” ์ €์ž ID๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ, ์ €์ž ID๊ฐ€ ๊ฐ™๋‹ค๋ฉด ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

select b.author_id, a.author_name, b.category, sum(s.sales*b.price) as total_sales
from book b 
    join author a on b.author_id = a.author_id
    join book_sales s on s.book_id = b.book_id
where date_format(s.sales_date, "%Y%m") = '202201'
group by b.author_id, b.category
order by b.author_id asc, b.category desc

 

๋ฐ˜์‘ํ˜•