Skip to main content

LeetCode 1158. Market Analysis I SQL Solution

Problem

LeetCode SQL Problem

  1. Market Analysis I

Users table

user_idjoin_datefavorite_brand
12018-01-01Lenovo
22018-02-09Samsung
32018-01-19LG
42018-05-21HP

Orders table

order_idorder_dateitem_idbuyer_idseller_id
12019-08-01 00:00:00.000412
22018-08-02 00:00:00.000213
32019-08-03 00:00:00.000323
42018-08-04 00:00:00.000142
52018-08-04 00:00:00.000134
62019-08-05 00:00:00.000224

Items table

item_iditem_brand
1Samsung
2Lenovo
3LG
4HP

Solution

Market Analysis I
-- Perform a LEFT JOIN to retrieve purchase orders in 2019 for each user
-- LEFT JOIN is required so we can output users who have made no purchase in 2019
SELECT U.user_id AS buyer_id
,U.join_date
,count(O.order_id) AS orders_in_2019
FROM Users AS U
LEFT JOIN Orders O ON U.user_id = O.buyer_id
AND YEAR(O.order_date) = 2019
GROUP BY U.user_id
,U.join_date
ORDER BY U.user_id

Query Output

buyer_idjoin_dateorders_in_2019
12018-01-011
22018-02-092
32018-01-190
42018-05-210