In Development: This textbook is currently
undergoing development and should not be used as an authoritative
source of... well, ANYTHING.
10 Window Functions
10.1 Learning Objectives
By the end of this chapter, students will be able to:
- Explain the difference between window functions and aggregate functions in terms of how output rows are produced.
- Write a window function using the
OVER()clause withPARTITION BYandORDER BY. - Apply
ROW_NUMBER(),RANK(), andDENSE_RANK()to assign row rankings within partitions. - Compare the behavior of
RANK()andDENSE_RANK()when rows share the same value, predicting the output of each. - Use
LAG()andLEAD()to access values from preceding and following rows within a result set. - Compute a running total or cumulative sum using
SUM()with anORDER BYinsideOVER(). - Define a custom window frame using
ROWS BETWEENorRANGE BETWEENto control which rows each calculation includes. - Compute a moving average by combining
AVG()with aROWS BETWEEN N PRECEDING AND CURRENT ROWframe. - Apply window functions within a CTE to perform multi-step analyses that reference ranked or lagged values in subsequent steps.
Stub: OVER, PARTITION BY, ORDER BY in window context, ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, running totals.