Lesson 2 of 3 Advanced Query Techniques

Window Functions for Rankings and Running Totals

This lesson explains the OVER clause, the ranking, aggregate and offset function families, and window frames.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how PARTITION BY, ORDER BY and frames define a window.
  • Distinguish between ROW_NUMBER, RANK and DENSE_RANK.
  • Identify when to use LAG, LEAD and explicit ROWS frames.

The OVER clause

A window function is followed by OVER ( [PARTITION BY ...] [ORDER BY ...] [frame] ). PARTITION BY divides rows into independent groups, such as per customer; ORDER BY defines the order within each partition; and the frame selects which rows around the current row an aggregate uses. Unlike GROUP BY, every input row stays in the output with the computed value next to it. Window functions are evaluated after WHERE, GROUP BY and HAVING, so they cannot be filtered directly in WHERE; the usual pattern computes them in a CTE or subquery and filters outside.

Spot the bug

Filtering a window function

Exam skills 1.3.2

Find the line that makes this top-3-per-category query fail.

Log in to try this activity Interactive activities are free with an account.

Function families

Window functions fall into three families, summarized in the following table.

FamilyFunctionsTypical use
RankingROW_NUMBER, RANK, DENSE_RANK, NTILETop N per group, deduplication, quartiles
AggregateSUM, AVG, COUNT, MIN, MAX with OVERRunning totals, moving averages, percentage of total
Offset and analyticLAG, LEAD, FIRST_VALUE, LAST_VALUE, PERCENT_RANK, PERCENTILE_CONTChange from previous period, gaps, medians

ROW_NUMBER assigns unique numbers even to ties; RANK gives ties the same number and skips the following numbers (1, 1, 3); DENSE_RANK does not skip (1, 1, 2). LAG(col, 1, 0) returns the previous row's value with a default when there is none.

Match the pairs

Choosing a window function

Exam skills 1.3.2

Match each requirement with the window function that meets it.

Log in to try this activity Interactive activities are free with an account.

Frames

With ORDER BY and an aggregate, the frame defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all rows with the same ORDER BY value as the current row and uses a slower on-disk spool. An explicit ROWS frame counts physical rows and is usually intended and faster.

SELECT OrderDate,
       DailyRevenue,
       SUM(DailyRevenue) OVER (ORDER BY OrderDate ROWS UNBOUNDED PRECEDING)           AS RunningTotal,
       AVG(DailyRevenue) OVER (ORDER BY OrderDate ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS Avg7Day,
       DailyRevenue - LAG(DailyRevenue, 1, 0) OVER (ORDER BY OrderDate)               AS ChangeFromPrevDay,
       DailyRevenue * 100.0 / SUM(DailyRevenue) OVER ()                               AS PctOfTotal
FROM Sales.vDailyRevenue;

The following diagram shows the rows each frame includes for one current row.

Window frames. ROWS UNBOUNDED PRECEDING sums every row from the start of the partition to the current row, giving a running total. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW covers the current row and the six before it, giving a seven-day moving average. With ORDER BY and no explicit frame, the default is RANGE UNBOUNDED PRECEDING, which includes ties and uses a slower spool, so an explicit ROWS frame is usually better.
An explicit ROWS frame is usually what is intended.
Scenario questions

Window frames

Exam skills 1.3.2

Choose the frame for each calculation.

Log in to try this activity Interactive activities are free with an account.
Worked example

Removing duplicates

A staging table contains duplicate customer rows with the same email address, loaded at different times. Only the most recently loaded row for each email must be kept. Which statement removes the others?

Number the rows per email with ROW_NUMBER() OVER (PARTITION BY Email ORDER BY LoadedUtc DESC) in a CTE and delete from the CTE where the number is greater than 1; deleting through a CTE deletes from its underlying table. RANK would give tied load times the same number and could keep two rows, and GROUP BY with MAX(LoadedUtc) finds the latest time but does not by itself delete the other rows.

Check yourself

For ordered values 10, 10, 20, what do RANK and DENSE_RANK return?

Show answer

RANK returns 1, 1, 3, and DENSE_RANK returns 1, 1, 2.

Exam Tips

Remember for the exam

  • Top N or latest row per group: ROW_NUMBER with PARTITION BY in a CTE.
  • Change from the previous row: LAG; next row: LEAD.
  • Use explicit ROWS frames for running totals and moving averages.
  • Window functions cannot be filtered in WHERE; filter outside a CTE.