Leetcode - 1098. Unpopular Books

문제

Loading...
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

정답

SELECT Books.book_id, name
FROM Books
JOIN (
    SELECT Books.book_id, IFNULL(Temp.total, 0) as total
    FROM Books
    LEFT JOIN (
        SELECT book_id, SUM(quantity) as total
        FROM Orders
        WHERE dispatch_date BETWEEN
            DATE_SUB('2019-06-23', INTERVAL 1 YEAR) AND '2019-06-23'
        GROUP BY book_id
    ) AS Temp
    ON Books.book_id = Temp.book_id
) AS Temp2
ON Books.book_id = Temp2.book_id
WHERE available_from < DATE_SUB('2019-06-23', INTERVAL 1 MONTH) AND total < 10

Solution 페이지에서 본 간결한 풀이이다. 10부 이하로 팔린 책을 GROUP BY 로 구하면, 해당 기간에 포함되지 않는 책의 경우는 결과에 나오지 않는다. 따라서 해당 기간에 10부 이상 팔린 책을 구한 다음, 메인 SELECT 문에서 이를 제외하는 방법으로 풀었다.

SELECT book_id, name
FROM Books
WHERE available_from < DATE_SUB('2019-06-23', INTERVAL 1 MONTH)
    AND book_id NOT IN (
        SELECT book_id
        FROM Orders
        WHERE dispatch_date BETWEEN
            DATE_SUB('2019-06-23', INTERVAL 1 YEAR) AND '2019-06-23'
        GROUP BY book_id
        HAVING SUM(quantity) >= 10
    )