I'm trying to get the closest subscription date to each order date (only for subscription dates that are before order dates) and also the corresponding cancellation date. Is there anyway to do this? I use mainly MySQL but any SQL variant that works in Snowflake should be ok.
My Code:
Select DISTINCT o.ORDER_ID, o.CUSTOMER_EMAIL, o.order_DATE min(subs.START_DATE)
FROM ORDERS o
INNER JOIN subscriptions subs
GROUP BY ORDER_ID, CUSTOMER_EMAIL
,ORDER_DATE
ON o.CUSTOMER_EMAIL = subscriptions.CUSTOMER_EMAIL
ORDERS Table:
| ORDER_ID | ORDER_DATE | CUSTOMER_EMAIL |
|---|---|---|
| 1234 | 20/02/2021 | jay@gmail.com |
Subscriptions table:
|SUBSCRIPTION_ID | START_DATE | CUSTOMER_EMAIL | CANCEL_DATE |
|----------------|------------|----------------|-------------|
|1236 | 20/03/2021 |jay@gmail.com | 20/04/2021|
|1232 | 19/02/2021 |jay@gmail.com | 19/03/2021|
|1219 | 20/01/2021 |jay@gmail.com | 29/01/2021|
Expected Result:
| ORDER_ID | ORDER_DATE | CUSTOMER_EMAIL | EARLIEST_SUBSCRIPTION_START | CLOSEST_SUBSCRIPTION_START | CLOSEST_SUBSCRIPTION_END |
|---|---|---|---|---|---|
| 1234 | 20/02/2021 | jay@gmail.com | 20/01/2021 | 19/02/2021 | 19/03/2021 |