+----------------+---------+
|Column Name |Type|+----------------+---------+
| user_id | int || join_date | date || favorite_brand | varchar |+----------------+---------+
user_id is the primarykey (columnwithuniquevalues) of this table.
This table has the info of the users of an online shopping website where users can sell and buy items.
Table: Orders
1
2
3
4
5
6
7
8
9
10
11
12
+---------------+---------+
|Column Name |Type|+---------------+---------+
| order_id | int || order_date | date || item_id | int || buyer_id | int || seller_id | int |+---------------+---------+
order_id is the primarykey (columnwithuniquevalues) of this table.
item_id is a foreignkey (reference column) to the Items table.
buyer_id and seller_id areforeign keys to the Users table.
Table: Items
1
2
3
4
5
6
7
+---------------+---------+
|Column Name |Type|+---------------+---------+
| item_id | int || item_brand | varchar |+---------------+---------+
item_id is the primarykey (columnwithuniquevalues) of this table.
Write a solution to find for each user, the join date and the number of orders they made as a buyer in 2019.
We need to count the number of orders each user made as a buyer in 2019. We use a LEFT JOIN to include users with zero orders, and filter orders by year.
SELECT u.user_id, u.join_date, COUNT(o.order_id) AS orders_in_2019
FROM Users u
LEFTJOIN Orders o
ON u.user_id = o.buyer_id ANDYEAR(o.order_date) =2019GROUPBY u.user_id, u.join_date;
1
2
3
4
5
SELECT u.user_id, u.join_date, COUNT(o.order_id) AS orders_in_2019
FROM Users u
LEFTJOIN Orders o
ON u.user_id = o.buyer_id ANDEXTRACT(YEARFROM o.order_date) =2019GROUPBY u.user_id, u.join_date;