Advertisement
Advanced SQL Server, Aggregate Functions & GROUP BY

How would you calculate a running total or a percentage of total using aggregate functions combined with window functions?

Short answer

You use a window function like SUM combined with an OVER clause to calculate a running total or a total across the whole result set without collapsing rows through GROUP BY, letting you show both individual row detail and an aggregated comparison value side by side in the same…

Save SQL Server mock interview
Advertisement
AModel answer
You use a window function like SUM combined with an OVER clause to calculate a running total or a total across the whole result set without collapsing rows through GROUP BY, letting you show both individual row detail and an aggregated comparison value side by side in the same result.
SELECT OrderId, Amount,
  SUM(Amount) OVER (ORDER BY OrderDate) AS RunningTotal,
  Amount * 100.0 / SUM(Amount) OVER () AS PercentOfTotal
FROM Orders;
Real-world example
A finance dashboard shows each order alongside a running total of revenue for the month and what percentage that single order represents of the overall total, all without losing any individual order detail.
Likely follow-ups
  • What is the difference between using GROUP BY and using a window function for this kind of calculation?
  • How does the ORDER BY inside OVER affect a running total calculation?
Related topics