47. Profitable Customers in 2021
A company maintains a revenue log for customers over different years. Youโve been asked to identify which customers had a positive revenue in the year 2021, to target them for loyalty programs or upsell opportunities.
You are given a Customers table that tracks:
โโโโโโโโโโโโโโโฆโโโโโโโโโโโ โ Column Name โ Type โ โ โโโโโโโโโโโโโโฌโโโโโโโโโโโฃ โ customer_id โ int โ โโโโโโโโโโโโโโโผโโโโโโโโโโโ โ year โ int โ โโโโโโโโโโโโโโโผโโโโโโโโโโโ โ revenue โ int โ โโโโโโโโโโโโโโโฉโโโโโโโโโโโ
- customer_id: Unique ID for the customer.
- year: Year for which the revenue is recorded.
- revenue: Revenue generated by the customer, which may be positive or negative.
- (customer_id, year) is the primary key.
Write an SQL query to return all customer_ids from the Customers table where positive revenue in the year 2021.
The result should be returned in any order.
Example 1:
Example:
Input:
Customers Table:
โโโโโโโโโโโโโโโฆโโโโโโโโโโโฆโโโโโโโโโโโ โ customer_id โ year โ revenue โ โ โโโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฃ โ 1 โ 2018 โ 50 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 1 โ 2021 โ 30 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 1 โ 2020 โ 70 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 2 โ 2021 โ -50 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 3 โ 2018 โ 10 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 3 โ 2016 โ 50 โ โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโ โ 4 โ 2021 โ 20 โ โโโโโโโโโโโโโโโฉโโโโโโโโโโโฉโโโโโโโโโโโ
Output:
โโโโโโโโโโโโโโโ โ customer_id โ โ โโโโโโโโโโโโโโฃ โ 1 โ โโโโโโโโโโโโโโโ โ 4 โ โโโโโโโโโโโโโโโ
Explanation:
- Customer 1: revenue = 30 โ(included)
- Customer 2: revenue = -50 โ(not included)
- Customer 3: no data for 2021 โ(not included)
- Customer 4: revenue = 20 โ(included)
Still unsure what the problem is asking ?
Letโs go through a few more examples, step by step, to make it clearer.