课程: SQL Practice: Window Functions

Solution: Calculate a running total - SQL教程

课程: SQL Practice: Window Functions

Solution: Calculate a running total

- [Instructor] To calculate a running sum, I added SUM PartySize OVER ORDER BY Date as Total. The sum of PartySize will count up how many people were in each reservation party as rows are returned from the database. Using OVER, we set the window that we want the aggregate function to work on, and we'll ensure that the items in that window are sorted by date. Here we would also have the opportunity to tell the database to only calculate the sum over specific groups and other things like that. But we'll see that later on. Without specifying a partition or range or anything, we'll just operate on the whole set of data as one unit sorted by date, one row at a time. So the first row of our result will have the first value for PartySize. The second row will have its own plus the previous value, and so on, adding up the PartySize field as rows are returned from the database. And the last row returned will have the grand total. I'll run this to see if it works. Looks like it does. Great. I can see how that aggregate function is operating row by row. Without using OVER, I'd just get back one row with a total of the PartySize field, and that's not what the challenge asked for. It asked for the running total, and that's what I have here.

内容