Back to results for “Window Functions”
SQL Server › Window Functions

How would you use window functions together to build a comprehensive sales analytics report showing running totals, rankings, and period over period comparisons all in a single query?

Advanced

Answer

You would combine several window functions in the same SELECT statement, each with its own appropriately configured OVER clause, such as SUM for a running total, RANK for identifying top performers within each category, and LAG for calculating change from the previous period, all calculated together efficiently in a single pass over the data rather than requiring several separate queries.
SELECT SalesPersonId, SaleMonth, Amount,
  SUM(Amount) OVER (PARTITION BY SalesPersonId ORDER BY SaleMonth) AS RunningTotal,
  RANK() OVER (PARTITION BY SaleMonth ORDER BY Amount DESC) AS MonthlyRank,
  Amount - LAG(Amount) OVER (PARTITION BY SalesPersonId ORDER BY SaleMonth) AS MonthOverMonthChange
FROM Sales;
Real-world example A sales analytics dashboard combines multiple window functions in a single efficient query, showing each salesperson's running total, their monthly rank among peers, and their change from the previous month all together in one comprehensive report.

Common follow-ups: How does combining multiple window functions in one query affect overall performance compared to running them separately?;How do you verify that a complex combination of window functions is producing correct results?