"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
Calculating Running StatisticsA running (or cumulative ) statistic is a row-by-row calculation that uses progressively more data values, starting with a single value (the first value), continuing with more data values in the order in which they're supplied, and ending with all the values. A running sum (total) and running average (mean) are the most common running statistics.Listing 9.10 calculates the running sum and running average of book sales, along with a cumulative count of data items. The query cross-joins two instances of the table titles, grouping the result by the first-table (t1) title IDs and limiting the second-table (t2) rows to ID values smaller than or equal to the t1 row to which they're joined. The intermediate cross-joined table, to which SUM(), AVG(), and COUNT() are applied, looks like this: Note that the running statistics don't change for title T10 because its sales value is null. The ORDER BY clause is necessary because GROUP BY doesn't sort the result implicitly. See Figure 9.10 for the result. Figure 9.10. Result of Listing 9.10.
Listing 9.10. Calculate the running sum, average, and count of book sales. See Figure 9.10 for the result.![]() Listing 9.11 calculates the moving average of price. See Figure 9.11 for the result. Each value in the result's moving-average column is the average of five values: the price in the current row and the prices in the four preceding rows (as ordered by seq). The first four rows are omitted because they don't have the required number of preceding values. You can adjust the values in the WHERE clause to cover any size averaging window. To make Listing 9.11 calculate a five-point moving average that averages each price with the two prices before it and the two prices after it, for example, change the WHERE clause to:
Figure 9.11. Result of Listing 9.11.
Listing 9.11. Calculate a moving average with a five-point window. See Figure 9.11 for the result.![]() Figure 9.12. Result of Listing 9.12.
Listing 9.12. Calculate inter-city distances from cumulative distances. See Figure 9.12 for the result.![]() |


