×

sql · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

SUM(...) OVER (ORDER BY day) builds a .

A running total grows as you go: the first day's takings, then the first two days together, and so on. It answers questions like how much the café has made so far this week.

Put ORDER BY inside OVER and the sum stops covering the whole result. Each row now adds itself to every row before it in that order. SUM(amount) OVER (ORDER BY day) gives the takings so far on each day.

Add PARTITION BY too, and every group keeps its own running total, starting from zero.

SELECT day, amount,
  SUM(amount) OVER (ORDER BY day) AS so_far
FROM takings
ORDER BY day;

Rows that tie in the window's ORDER BY are added in together, so give every row its own place.