Skip to main content

LeetCode 1098. Unpopular Books SQL Solution

Problem

LeetCode SQL Problem

  1. Unpopular Books

Books table

book_idnameavailable_from
1Kalila And Demna2010-01-01
228 Letters2012-05-12
3The Hobbit2019-06-10
413 Reasons Why2019-06-01
5The Hunger Games2008-09-21

Orders table

order_idbook_idquantitydispatch_date
1122018-07-26
2112018-11-05
3382019-06-11
4462019-06-05
5452019-06-20
6592009-02-02
7582010-04-13

Solution

Unpopular Books
SET @today = '2019-06-23';
SET @one_month_ago = DATE_ADD(@today, INTERVAL -30 DAY);
SET @one_year_ago = DATE_ADD(@today, INTERVAL -1 YEAR);

-- Report the books that have sold less than 10 copies in the last year
SELECT B.book_id
,B.name
FROM Books AS B
LEFT JOIN Orders AS O ON B.book_id = O.book_id
AND O.dispatch_date BETWEEN @one_year_ago
AND @today
-- Exclude books that have been available for less than 1 month from today.
-- Assume today is 2019-06-23.
WHERE B.available_from < @one_month_ago
GROUP BY B.book_id
,B.name
HAVING count(O.order_id) <= 10

Query Output

book_idname
228 Letters
1Kalila And Demna
5The Hunger Games