SQL
Lab
Amazon Easy Window Functions Classic

Running
Total Of
Sales

Calculate the running total of sales by date.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
sale_datedateDate of the sale.
amountintegerSale amount.

Sample Data

Input
Output

Sample Input: sales
sale_dateamount
2024-01-01100
2024-01-02200
2024-01-03150
2024-01-04300
2024-01-05250
2024-01-06100
Expected Output
sale_daterunning_total
2024-01-01100
2024-01-02300
2024-01-03450
2024-01-04750
2024-01-051000
2024-01-061100

SQL Editor

Run
Query

postgresql
Waiting for query

sale_daterunning_total
2024-01-01100
2024-01-02300
2024-01-03450
2024-01-04750
2024-01-051000
2024-01-061100

Hints

Unlock
Clues

Hint 01: Sort the sales by date before calculating the total.
Hint 02: Use SUM(amount) OVER (ORDER BY sale_date).
Hint 03: Return both the date and the cumulative amount.

Solution

Locked
Answer

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

Step By
Step

01

Sort the sales by date so the running total follows the correct order.

02

Use a window SUM to carry each amount forward through the rows.

03

Return the sale date alongside the cumulative amount.

Related Questions

Keep
Solving