Brightlane's operations team tracks how the cumulative order count grows as orders accumulate by id.
Write a query to return the ID and status of every order, plus the running count of orders from the first record through that order in order of id.
Assumptions:
- The
orderstable has one row per order with anidand astatus. - Orders are processed in ascending
idorder. The running count at each row is the number of orders whoseidis less than or equal to that row'sid.
Output:
- One row per order, with columns
id,status, andrunning_count.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
status,
COUNT(*) OVER (
ORDER BY
id
) AS running_count
FROM
orders The shape
COUNT(*) OVER (ORDER BY id) attaches a running order count to every row. Each row sees how many orders have been recorded through and including its own id. The ORDER BY id inside OVER is what turns a static total count into a value that grows row by row.
Clause by clause
SELECT id, statusreturns each order's identifier and its status unchanged. The window count is computed alongside; the original rows stay intact.COUNT(*) OVER (ORDER BY id) AS running_countcounts rows from the start of the table up to and including the current row, inidorder.COUNT(*)here counts rows, not a particular column, so every row contributes1to the accumulator. The first row carriesrunning_count = 1, the second carries2, the third carries3, and so on. WhereCOUNT(*)withoutOVERwould collapse the table into a single number, theOVER (ORDER BY id)clause keeps every row and grows the count asidadvances.FROM ordersreads every order. Every row in the table contributes to the running count.
You practiced COUNT(*) OVER (ORDER BY ...) — running count over an ordered window; each row sees the count of records up to and including itself.