Produce a continuous daily calendar from the earliest to the latest sale_date with each day's total amount. Generate the dates with a recursive CTE that starts at the minimum sale_date and adds one day at a time until it reaches the maximum. Days with no sales must still appear, with a total of 0.
Input Table(s)
sales
| Column | Type | Meaning |
|---|
| sale_id | INT | Sale identifier |
| sale_date | DATE | Day of the sale (never NULL) |
| amount | DECIMAL(10,2) | Sale amount (never NULL) |
Key: sale_id is the primary key. Several sales can share a date.
Output Contract
Return these columns in this order, one row per calendar day from the earliest sale_date to the latest, inclusive:
| Column | Rule |
|---|
| calendar_date | The day, as a DATE |
| total_amount | Sum of amount over that day's sales; 0 for a day with no sales |
Sort by calendar_date ascending.
Example
sales
| sale_id | sale_date | amount |
|---|
| 1 | 2024-01-01 | 100.00 |
| 2 | 2024-01-01 | 50.00 |
| 3 | 2024-01-03 | 200.00 |
Expected result:
| calendar_date | total_amount |
|---|
| 2024-01-01 | 150.00 |
| 2024-01-02 | 0.00 |
| 2024-01-03 | 200.00 |
The range spans 2024-01-01 to 2024-01-03. Jan 1 has two sales summing to 150.00, Jan 2 has no sales so it appears with 0, and Jan 3 has 200.00.
Constraints and Clarifications
-
sales
has at least one row. A single row, or several rows on one date, yields a single calendar day.
-
sale_date
values span at most 366 days.
-
amount
is non-negative.
-
Every day in the range appears exactly once, whether it has zero, one or many sales.