All problems

The Running Total

hardSQLWindow FunctionsDates

The chart the board at Whetcode Supply actually looks at is the one that only goes up: money taken so far, plotted one sale at a time from the shop's first order onward. Each point is everything earned up to and including that order, so the line climbs by the value of each new sale and never falls.

The slide shows the opening stretch — the first five sales, back when each one visibly moved the line. Two of those sales landed on the same day, so the sequence needs a rule for which of them comes first.

orders — one row per order. customer_id is the id of the customer who placed it, product_id the id of the item bought, quantity how many units of that item, and order_date the day it was placed. An order row covers one item only.

id customer_id product_id quantity order_date
1 1 1 2 2023-02-01
2 1 4 1 2023-02-01
3 2 2 1 2023-02-10
4 3 3 3 2023-03-05
5 4 5 5 2023-03-11
6 1 3 1 2023-04-02
7 5 1 4 2023-05-20
8 2 5 2 2023-05-22
9 3 4 1 2023-06-01
10 5 2 1 2023-06-15

products — the catalogue, one row per item on sale. price is what a single unit costs, in dollars.

id name category price
1 Wireless Mouse electronics 25.0
2 Standing Desk furniture 350.0
3 Desk Lamp furniture 40.0
4 Mechanical Keyboard electronics 85.0
5 Notebook Set office 12.0

The tables already exist in the database — there is nothing to create or load.

Task: Write a query returning two columns, order_date (the day the order was placed, exactly as stored) and cumulative_revenue (everything the shop had taken up to and including that order, rounded to two decimal places), returning only the first five rows. Take the orders oldest first, using the order's own id to separate two placed on the same day, smaller id first. An order's own value is its item's price times its number of units. Because two orders share a date, order_date appears twice in the output with two different running totals.

Example output — shape only, on invented orders. The first two share a date and carry two different running figures, because the total advances one order at a time rather than one day at a time:

order_date cumulative_revenue
2019-01-05 90
2019-01-05 315
2019-01-19 480
2019-02-02 725
2019-02-14 940

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…