👉 오늘 한 일
프로그래머스 SQL
1. 년, 월, 성별 별 상품 구매 회원 수 구하기 💡
SELECT YEAR(b.sales_date) AS year,
MONTH(b.sales_date) AS month,
IF(gender = 1, 1, 0) AS gender,
COUNT(DISTINCT(b.user_id)) AS users
FROM user_info a
JOIN online_sale b
ON a.user_id = b.user_id
WHERE gender IS NOT NULL
GROUP BY year, month, gender
ORDER BY year, month, gender
2. 저자 별 카테고리 별 매출액 집계하기 📌
SELECT a.author_id,
b.author_name,
a.category,
a.price * SUM(c.sales) AS total_sales
FROM book a
JOIN author b
ON a.author_id = b.author_id
JOIN book_sales c
ON a.book_id = c.book_id
WHERE DATE_FORMAT(c.sales_date, "%Y-%m") = "2022-01"
GROUP BY a.author_id, a.category
ORDER BY a.author_id, a.category DESC
- 다시 생각한 풀이
- 나머지는 모두 같으나 총 판매량을 구할 때 가격 * 판매량을 모두 더해줌. GROUP BY를 작가id와 카테고리만으로 묶기 때문에 이게 옳은 방법임
SELECT a.author_id,
b.author_name,
a.category,
SUM(a.price * c.sales) AS total_sales
FROM book a
JOIN author b
ON a.author_id = b.author_id
JOIN book_sales c
ON a.book_id = c.book_id
WHERE DATE_FORMAT(c.sales_date, "%Y-%m") = "2022-01"
GROUP BY a.author_id, a.category
ORDER BY a.author_id, a.category DESC