|
| 1 | +-- we need customer ids from 2 separate tables using 'and' condition |
| 2 | +-- 1st table- get sum of expenditures of all customers in June 2020, filter by customers whose sum >= 100 |
| 3 | +-- 2nd table- get sum of expenditures of all customers in July 2020, filter by customers whose sum >= 100 |
| 4 | +-- pull all customers who are in table1 AND table 2 |
| 5 | + |
| 6 | +select c.customer_id, c.name |
| 7 | +from Customers |
| 8 | +where customer_id in |
| 9 | + (select customer_id |
| 10 | + from Orders o |
| 11 | + join Product p |
| 12 | + on o.product_id = p.product_id |
| 13 | + where left(order_date, 7) = '2020-06' |
| 14 | + group by customer_id |
| 15 | + having sum(quantity*price) >= 100) |
| 16 | + and customer_id in |
| 17 | + (select customer_id, sum(quantity*price) |
| 18 | + from Orders o |
| 19 | + join Product p |
| 20 | + on o.product_id = p.product_id |
| 21 | + where left(order_date, 7) = '2020-07' |
| 22 | + group by customer_id |
| 23 | + having sum(quantity*price) >= 100) |
| 24 | + |
| 25 | +--------------------------------------------------------------------------------------------------------------------- |
| 26 | + |
| 27 | +-- create a temp table- join all tables |
| 28 | +-- create 2 additional columns- expenditure in June and in July- CASE, AGGREGATE |
| 29 | +-- in the main query, pull customer ids where expenditure in both columns are >= 100 |
| 30 | + |
| 31 | +with CTE as(select c.customer_id, c.name, |
| 32 | + sum(case when left(o.order_date, 7) = '2020-06' then p.price*o.quantity else 0 end) june_spent, |
| 33 | + sum(case when left(o.order_date, 7) = '2020-07' then p.price*o.quantity else 0 end) july_spent |
| 34 | +from Customers c |
| 35 | +join Orders o |
| 36 | +on c.customer_id = o.customer_id |
| 37 | +join Product p |
| 38 | +on p.product_id = o.product_id |
| 39 | +group by 1) |
| 40 | + |
| 41 | +select customer_id, name |
| 42 | +from CTE |
| 43 | +where june_spent >= 100 and july_spent >= 100 |
| 44 | + |
| 45 | + |
| 46 | +-- amazon- 1 |
0 commit comments