Created
December 5, 2023 20:43
-
-
Save divinorum-webb/e7a5120fa5296f221093a6c7b4922a73 to your computer and use it in GitHub Desktop.
devyx-sql-example-cte
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH high_value_customers AS ( | |
SELECT | |
customer_id | |
, SUM(total_revenue) AS total_revenue | |
FROM transaction_details td | |
LEFT JOIN customer_details cd | |
ON td.card_id = cd.card_id | |
GROUP BY 1 | |
ORDER BY 2 DESC | |
HAVING total_revenue > 500 | |
), new_customers AS ( | |
SELECT | |
customer_id | |
, MAX(DATEDIFF(CURDATE(), date_first_seen)) AS days_since_first_seen | |
FROM customer_details | |
GROUP BY 1 | |
HAVING days_since_first_seen < 90 | |
) | |
SELECT | |
hvc.customer_id | |
, total_revenue | |
, days_since_first_seen | |
FROM high_value_customers hvc | |
INNER JOIN new_customers nc | |
ON hvc.customer_id = nc.customer_id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment