Created
May 13, 2022 14:35
-
-
Save thomasnield/16881ac08cd1586277dadf46ffad4772 to your computer and use it in GitHub Desktop.
recursive_date_orders.sql
This file contains hidden or 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 RECURSIVE my_dates(x) AS ( | |
SELECT date('2000-01-01') | |
UNION ALL | |
SELECT date(x, '+1 day') | |
FROM my_dates | |
WHERE x < '2030-12-31' | |
), | |
all_combos AS ( | |
SELECT | |
x AS CALENDAR_DATE, | |
PRODUCT_ID | |
FROM PRODUCT | |
CROSS JOIN my_dates | |
WHERE x BETWEEN '2017-01-01' and '2017-03-31' | |
), | |
totals AS ( | |
SELECT ORDER_DATE, | |
PRODUCT_ID, | |
SUM(QUANTITY) as TOTAL_QTY | |
FROM CUSTOMER_ORDER | |
GROUP BY 1, 2 | |
) | |
SELECT CALENDAR_DATE, | |
all_combos.PRODUCT_ID, | |
coalesce(TOTAL_QTY, 0) AS TOTAL_QTY | |
FROM all_combos LEFT JOIN totals | |
ON all_combos.CALENDAR_DATE = totals.ORDER_DATE | |
AND all_combos.PRODUCT_ID = totals.PRODUCT_ID | |
ORDER BY CALENDAR_DATE, all_combos.PRODUCT_ID |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment