Create a new table based on another two tables in SQL. The first table USER has one variable
user_id | purchase_time
-----------------------------
Marta | 10/20/2019
Steve | 10/21/2019
Michael | 10/18/2019
And COUPON table has two variables
user_id | coupon_id | coupon_time
-------------------------------------------
Marta | 12345 | 10/21/2019
Steve | 12356 | 10/18/2019
Marta | 12365 | 10/01/2019
Michael | |
The problem is to create a new table USER_SUMMARY. Count the numbers of coupons received before and after purchase_time, and count the total coupons received. If no coupon received after puchase_time, count 0. The final created a table should like below:
user_id | purchase_before_coupon | purchase_after coupon | total_coupons
--------------------------------------------------------------------------------------
Marta | 1 | 1 | 2
Steve | 0 | 1 | 1
Michael | 0 | 0 | 0
Should not be complicated if done in Python or R, but I don't quite know how to do it in SQL syntax. Thanks in advance!