Table Schema
Inspect
Table
| Column | Type | Description |
|---|---|---|
| sale_date | date | Date of the sale. |
| amount | integer | Sale amount. |
Calculate the running total of sales by date.
Table Schema
| Column | Type | Description |
|---|---|---|
| sale_date | date | Date of the sale. |
| amount | integer | Sale amount. |
Sample Data
| sale_date | amount |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-02 | 200 |
| 2024-01-03 | 150 |
| 2024-01-04 | 300 |
| 2024-01-05 | 250 |
| 2024-01-06 | 100 |
| sale_date | running_total |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-02 | 300 |
| 2024-01-03 | 450 |
| 2024-01-04 | 750 |
| 2024-01-05 | 1000 |
| 2024-01-06 | 1100 |
SQL Editor
| sale_date | running_total |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-02 | 300 |
| 2024-01-03 | 450 |
| 2024-01-04 | 750 |
| 2024-01-05 | 1000 |
| 2024-01-06 | 1100 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
SELECT sale_date, SUM(amount) OVER (ORDER BY sale_date) AS running_total FROM sales ORDER BY sale_date;
Explanation
Sort the sales by date so the running total follows the correct order.
Use a window SUM to carry each amount forward through the rows.
Return the sale date alongside the cumulative amount.
Related Questions