Running totals
Add up as you go down the rows.
SUM(...) OVER (ORDER BY ...) gives each row the total so far.
A reading challenge per genre: for each book show genre, title, year and pages_so_far, the pages read in that genre up to and including it, oldest first.
| book_id | title | author | genre | year | pages |
|---|---|---|---|---|---|
| 1 | Pride and Prejudice | Jane Austen | Romance | 1813 | 432 |
| 2 | The Fault in Our Stars | John Green | Romance | 2012 | 313 |
| 3 | Angels & Demons | Dan Brown | Thriller | 2000 | 616 |
| 4 | Mockingjay | Suzanne Collins | Science Fiction | 2010 | 390 |
| 5 | Carrie | Stephen King | Horror | 1974 | 200 |
| 6 | Charlotte's Web | E.B. White | Children | 1952 | 184 |
| 7 | 1984 | George Orwell | Science Fiction | 1949 | 328 |
| 8 | The Fellowship of the Ring | J.R.R. Tolkien | Fantasy | 1954 | 423 |
| 9 | The Time Machine | H.G. Wells | Science Fiction | 1895 | 118 |
| 10 | Dune | Frank Herbert | Science Fiction | 1965 | 412 |
| 11 | Dracula | Bram Stoker | Horror | 1897 | 418 |
Run your query to see the result table.
Press the green Run button or Ctrl+Enter.
How SUM, OVER works
SUM(pages) OVER (ORDER BY year) adds up the pages of every row so far, oldest first.
| title | year | pages | pages_so_far | |
|---|---|---|---|---|
| Frankenstein | 1818 | 280 | 280 | first book: just its pages |
| Dracula | 1897 | 418 | 698 | 280 + 418 |
| Brave New World | 1932 | 311 | 1009 | 698 + 311 |
| Dune | 1965 | 412 | 1421 | 1009 + 412 |
| Carrie | 1974 | 200 | 1621 | 1421 + 200 |
| The Hunger Games | 2008 | 374 | 1995 | 1621 + 374 |
query
SELECT title, year, pages, SUM(pages) OVER (ORDER BY year) AS pages_so_far FROM books;
Every row stays: GROUP BY would squash each genre into one row instead.
How do I make a running total?
SUM(pages) OVER (ORDER BY year)Each row adds up its own value and every row before it, in the
ORDER BYorder. Every row stays in the result.What if I leave out
ORDER BY?SUM(pages) OVER ()puts the grand total on every row. Handy for percentages:pages * 100.0 / SUM(pages) OVER ().Can it restart for each group?
Yes:
OVER (PARTITION BY genre ORDER BY year)keeps a separate running total per genre.What about ties in the
ORDER BY?Rows that tie are added together, so they show the same total. Write
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWinsideOVERto add them one at a time.How is this like Excel?
The classic running total
=SUM($F$2:F2)filled down, with the first cell locked and the last one moving.
Know someone fighting with a spreadsheet? Send them this page.