[업무 지식]/MySQL
[JOIN] 저자 별 카테고리 별 매출액 집계하기
에디터 윤슬
2024. 10. 14. 10:00
링크
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,
author_name,
category,
sum(price * sales) as total_sales
from book b
join author a on b.author_id = a.author_id
join book_sales s on b.book_id = s.book_id
where sales_date like '%2022-01%'
group by 1, 2, 3
order by 1, 3 desc
정답 2
with combined as (
select b.book_id,
b.author_id,
b.category,
(b.price * a.sales) as total_sales
from book_sales a
join book b on a.book_id = b.book_id
where date_format(sales_date, '%Y-%m') = '2022-01'
)
select a.author_id,
a.author_name,
c.category,
sum(c.total_sales)
from combined c
join author a on c.author_id = a.author_id
group by a.author_id, c.category
order by a.author_id, category desc
해설
- JOIN을 바로 이어서 붙여 3개의 테이블을 사용한다.
새롭게 이해한 내용
- JOIN을 따로 별칭을 붙이지 않고 바로 옆에 붙여서도 사용할 수 있다.