2022년 1월의 카테고리 별 도서 판매량을 합산하고, 카테고리(CATEGORY), 총 판매량(TOTAL_SALES) 리스트를 출력하는 SQL문을 작성해주세요.
결과는 카테고리명을 기준으로 오름차순 정렬해주세요.
SELECT * FROM BOOK
SELECT * FROM BOOK_SALES
SELECT bk.category , sum(bs.sales) AS TOTAL_SALES FROM BOOK bk LEFT JOIN BOOK_SALES bs ON bk.book_id = bs.book_id GROUP BY bk.category
💡 설명
- BOOK 테이블과 BOOK_SALES 테이블의 book_id 컬럼을 사용해 LEFT JOIN
FROM BOOK bk LEFT JOIN BOOK_SALES bs ON bk.book_id = bs.book_id
- 판매량을 구하기 위해 SUM()함수를 사용하고 'TOTAL_SALES'라는 명칭을 붙혀줌
sum(bs.sales) AS TOTAL_SALES
- category 별로 묶기 위해 GROUP BY를 사용함
SELECT bk.category ...(생략) GROUP BY bk.category
SELECT bk.category , sum(bs.sales) AS TOTAL_SALES FROM BOOK bk LEFT JOIN BOOK_SALES bs ON bk.book_id = bs.book_id WHERE DATE_FORMAT(sales_date, '%Y-%m') = '2022-01' GROUP BY bk.category
SELECT bk.category , sum(bs.sales) AS TOTAL_SALES FROM BOOK bk LEFT JOIN BOOK_SALES bs ON bk.book_id = bs.book_id WHERE MONTH(sales_date) = '1' GROUP BY bk.category
SELECT bk.category , sum(bs.sales) AS TOTAL_SALES FROM BOOK bk LEFT JOIN BOOK_SALES bs ON bk.book_id = bs.book_id WHERE DATE_FORMAT(sales_date, '%Y-%m') = '2022-01' GROUP BY bk.category ORDER BY bk.category