OVER() & Ranking
Four rows in orders hold amounts 99.00, 42.00, 42.00, 17.50, and totalling them folds the four into one number, 200.50. Total them a second way and all four rows stay, each now carrying that 200.50 beside it.
- ▸Same
SUM(amount), same 200.50, but one phrasing returns one row, the other all four with the total on each. - ▸Order four rows by amount, two tied at 42.00, and three numberings read 1,2,3,4 then 1,2,2,4 then 1,2,2,3.
- ▸
WHERE rn = 1is rejected: the number does not exist yet when the filter runs.
Four rows sit in orders, with amounts 99.00, 42.00, 42.00, and 17.50. Add them and you get one number for the whole table: 200.50. Grouping does this by folding the four rows into a single result row, the collapse from the aggregation unit: many rows in, one row out.
Now ask for something grouping cannot give you: the same 200.50, but printed next to every original row, with all four rows still there. You want each order's own amount AND the whole-table total side by side, four rows wide, nothing folded away.
SELECT id, amount, SUM(amount) OVER () AS total FROM orders; -- id amount total -- 101 99.00 200.50 -- 102 42.00 200.50 -- 103 42.00 200.50 -- 104 17.50 200.50
The aggregate still ran, it still added the four amounts to 200.50, but the rows did not merge. Each kept its identity and gained a column. Four rows in, four rows out. That is the whole move this unit is built on, and the rest of the topic is variations on it: an aggregate that computes across rows without collapsing them.