본문 바로가기

DB/Programmers SQL Kit

저자 별 카테고리 별 매출액 집계하기

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

 

- BOOK, AUTHOR, BOOK_SALES 테이블의 저자id, 저자명, 카테고리, 매출액을 조회한다.

단, 2022년 1월 판매 데이터를 기준으로 저자별, 카테고리별 매출액을 구할 것이며, 저자id 기준 오름차, 카테고리 기준 내림차 정렬한다.

1. 2022년 1월의 판매 데이터를 뽑아낸다. 이후 book_id를 기준으로 book과 book_sales 테이블을 조인한다.

2. 카테고리 저자ID 두 값을 기준으로 그룹핑하여 sum 함수를 사용해 그룹별 총 매출액을 구한다.

3. 그룹핑한 테이블과 AUTHOR 테이블을 author_id를 기준으로 조인하여 필요 값을 조인한다.

- SQL

mysql : SELECT a.author_id, a.author_name, cts.category, cts.total_sales
FROM (
    SELECT b.category, b.author_id, SUM(b.price * bs.sales) total_sales
    FROM BOOK b, BOOK_SALES bs
    WHERE DATE_FORMAT(bs.sales_date, '%Y-%m') = '2022-01' AND b.book_id = bs.book_id
    GROUP BY b.category, b.author_id
) cts, AUTHOR a
WHERE cts.author_id = a.author_id
ORDER BY author_id ASC, category DESC;

oracle :  SELECT a.author_id, a.author_name, cts.category, cts.total_sales
FROM (
    SELECT b.category, b.author_id, SUM(b.price * bs.sales) total_sales
    FROM BOOK b, BOOK_SALES bs
    WHERE TO_CHAR(bs.sales_date, 'YYYY-mm') = '2022-01' AND b.book_id = bs.book_id
    GROUP BY b.category, b.author_id
) cts, AUTHOR a
WHERE cts.author_id = a.author_id
ORDER BY author_id ASC, category DESC;