Brightlane's finance team wants every order's amount displayed alongside the company-wide revenue total for at-a-glance comparison.
Write a query to return the ID and amount of every order, plus the combined total amount across every order on each row.
Assumptions:
- The
orderstable has one row per order with anidand atotal_amount. - The grand total is the combined
total_amountacross every order in the table. The same value should appear on every output row.
Output:
- One row per order, with columns
id,total_amount, andgrand_total.
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,
total_amount,
SUM(total_amount) OVER () AS grand_total
FROM
orders The shape
SUM(total_amount) OVER () computes the company-wide revenue total once and copies that single value onto every output row, leaving each order's own id and total_amount untouched. The empty parentheses after OVER are what make the window the entire result set.
Clause by clause
SELECT id, total_amountreturns each order's identifier and its individual amount, one row per order with no collapsing.- The window column is:
SUM(total_amount) OVER () AS grand_totalSUM runs across the rows in the window. OVER () with nothing inside it defines the window as every row in the result, so the sum is the combined total_amount across the whole orders table. The same scalar lands in grand_total on every row.
FROM ordersreads every order. There is noWHEREbecause the grand total is over every order in the table.
Why this and not GROUP BY with a single total
A bare SELECT SUM(total_amount) FROM orders returns one row, the grand total alone. The finance team needs the grand total alongside every order's individual amount, not instead of it. OVER () is what keeps every row in the output while still attaching the aggregate. The empty window is the load-bearing piece.
You practiced SUM(...) OVER () — compute a single total across the entire result and replicate it onto every row, without collapsing the rows themselves.