Create Running Totals Using Window Functions

Brett Cassette
InstructorBrett Cassette

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

How could your Kickstarter-type site list the running total for each contribution next to it? Using window functions of course! The default behavior for aggregations under window functions is to create running totals.

[00:00] If we have a Kickstarter type site where we have projects and we have backers, and these backers are contributing to the projects, we have a list of each of their contributions. Maybe we want to show a running total of the contributions. We can do that with a sum function, sum of the contributions.

[00:23] We use our over clause to partition by the project ID. As we've seen in the past, if we don't include any kind of order clause, now the sum is going to be the same for the entire row, or for the entire window, and that's not what we want here. We'll have to have some kind of order by here, so we can say, "Order by contribution," which, by default, will be ascending.

[00:46] We see we start with 5.5, add 25. It gives us 30.5, etc., etc., for the entire window. This also works fine if we want to do it as a descending. We just have to make sure to include the order by, or some sort of explicit frame clause, which we'll talk about next.