Running Total of Sales per Product by Month
Company: Goldman Sachs
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
For every row in `Sales`, return `product_id`, `sale_month`, `amount`, and `running_total`: the cumulative `amount` for that product up to and including that month. Order by `product_id` ascending, then `sale_month` ascending.
```hint Keep every row
You need a sum over the earlier months of the same product, but the output still has one row per sale. Think about which SQL feature aggregates without collapsing rows.
```
### Input Table(s)
Table: `Sales`
| Column | Type | Meaning |
| --- | --- | --- |
| sale_id | INT | Identifier of the sale. Primary key. |
| product_id | INT | Product that was sold. NOT NULL. |
| sale_month | DATE | Month the sale is recorded in. NOT NULL. |
| amount | DECIMAL(10,2) | Sale amount. NOT NULL, never negative. |
Keys: `sale_id` is the primary key, and each `(product_id, sale_month)` pair appears at most once.
### Output Contract
- Columns, in this order: `product_id`, `sale_month`, `amount`, `running_total`.
- One output row per row of `Sales`.
- `running_total` is the sum of `amount` over all rows of the same `product_id` whose `sale_month` is on or before the current row's `sale_month`.
- Order by `product_id` ascending, then `sale_month` ascending. This ordering is unique because the pair is unique.
- No rounding is needed: sums of `DECIMAL(10,2)` values stay exact at two decimal places.
### Example
`Sales`
| sale_id | product_id | sale_month | amount |
| --- | --- | --- | --- |
| 1 | 10 | 2024-01-01 | 100.00 |
| 2 | 10 | 2024-03-01 | 50.00 |
| 3 | 20 | 2024-02-01 | 30.00 |
| 4 | 10 | 2024-02-01 | 25.50 |
| 5 | 20 | 2024-01-01 | 0.00 |
Expected result
| product_id | sale_month | amount | running_total |
| --- | --- | --- | --- |
| 10 | 2024-01-01 | 100.00 | 100.00 |
| 10 | 2024-02-01 | 25.50 | 125.50 |
| 10 | 2024-03-01 | 50.00 | 175.50 |
| 20 | 2024-01-01 | 0.00 | 0.00 |
| 20 | 2024-02-01 | 30.00 | 30.00 |
Product 10 accumulates 100.00, then 125.50 after February, then 175.50 after March. Its rows are stored out of month order, so the running total follows `sale_month`, not `sale_id`. Product 20 starts its own total from zero.
### Constraints and Clarifications
- The table has between 1 and 10,000 rows.
- `amount` is non-negative, and no column contains NULLs.
- Each `(product_id, sale_month)` pair is unique, so two rows of the same product never share a month.
- A product with a single row has `running_total` equal to its `amount`.
- Each product's total starts over; the running total never carries across products.
Overview: Write a SQL query that returns every sale with a cumulative amount for its product, accumulated month by month and sorted by product and month. It tests window aggregates, partitioning, frame clauses, and keeping one output row per input row.