Español Practice SQL

SQL running totals and share of total

SUM with OVER keeps every row and puts a total next to it.

SQL skills · Window functions

Practice this nowLearn it step by step

Free. No sign up. Your progress stays in this browser.

What you will learn

With ORDER BY inside OVER, the sum grows row by row: a running total. With empty brackets, it is the grand total on every row.

Dividing by that grand total gives each row’s share in percent.

The basics

SUM with OVER keeps every row and adds a total next to it.

SELECT due_date, amount,
  SUM(amount) OVER (ORDER BY due_date) AS running_total,
  ROUND(100.0 * amount / SUM(amount) OVER (), 1) AS pct_of_total
FROM invoices

With ORDER BY inside OVER, the sum grows row by row. With empty brackets, it is the grand total on every row. PARTITION BY restarts the sum for each group.

Write 100.0, not 100: in many databases a whole number divided by a whole number drops the decimals.

Worked examples

Example 1

Running total of shipped units by date.

SELECT ship_date, quantity,
  SUM(quantity) OVER (ORDER BY ship_date) AS running_total
FROM shipments

The last row equals the grand total.

Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.

Try a task

Common mistakes

  • Dividing whole numbers and losing the decimals. Write 100.0.
  • Forgetting PARTITION BY when each group should start from zero.
  • Using GROUP BY, which collapses the rows you wanted to keep.

Where you will use it at work

  • Finance: cumulative revenue this year.
  • Marketing: share of spend per campaign.
  • Operations: cumulative units shipped.

Questions people ask

What happens with ties in the ORDER BY date?

Rows with the same date can get the same running total. Add a second column to make the order unique.

Can I do a moving average?

Yes: AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).

Does this work in every database?

Yes, in all modern ones.

Ready to write it yourself?

Practice Running totals and shares

Related guides