Return each orderdate with that days total amount and a running cumulative total across dates, in date order. Table…
SQLLevel: IntermediateWindow functions
Return each order_date with that days total amount and a running cumulative total across dates, in date order.
Table definitions (from the source exercise):
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Daily totals in a CTE, then SUM OVER (ORDER BY date).
WITH daily AS (
SELECT order_date, SUM(amount) AS day_total
FROM orders GROUP BY order_date
)
SELECT order_date, day_total,
SUM(day_total) OVER (ORDER BY order_date) AS running_total
FROM daily
ORDER BY order_date;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT