Dev/SQL
[프로그래머스, Oracle] 저자별 카테고리별 매출 집계하기
잼카이브
2024. 4. 29. 01:34
https://school.programmers.co.kr/learn/courses/30/lessons/144856
내가 쓴 코드
-- 코드를 입력하세요
SELECT
a.author_id AS AUTHOR_ID,
a.author_name AS AUTHOR_NAME,
b.category AS CATEGORY,
SUM(b.price * bs.sales) AS TOTAL_SALES
FROM book b, author a, book_sales bs
WHERE
b.author_id = a.author_id
AND b.book_id = bs.book_id
AND to_char(bs.sales_date, 'yyyymm') = '202201'
GROUP BY b.category, a.author_name, a.author_id
ORDER BY AUTHOR_ID, CATEGORY DESC
왠지 비효율적인 것 같다.
to_char는 까먹고 있었다.
가상테이블로 쓰는 사람의 코드를 발견했다. 가독성이 좋다.
with Temp as (
SELECT
b.book_id,
b.category,
b.author_id,
a.author_name,
bs.sales * b.price AS total
FROM
BOOK b
JOIN AUTHOR a ON b.author_id = a.author_id
JOIN BOOK_SALES bs ON b.book_id = bs.book_id
WHERE
to_char(bs.sales_date, 'yyyymm') = '202201'
)
SELECT
t.author_id,
t.author_name,
t.category,
sum(t.total)
FROM Temp t
GROUP BY
t.author_id,
t.author_name,
t.category
ORDER BY
t.author_id,
t.category DESC
특이한 것은 원래 오라클이 그런건지 모르겠는데 가상테이블 with구문 내 FROM 절에서 JOIN ON 구문 없이 FROM에 콤마 구분하고 WHERE절에 조인 필터만 걸면 작동이 안 된다.