Window Functions

What is a Window Function?

A window function performs a calculation across a set of rows related to the current row, without collapsing them like GROUP BY does. Every row keeps its identity and gets an extra calculated value.

function_name(...) OVER (
  [PARTITION BY column(s)]
  [ORDER BY column(s)]
  [frame clause]
)

GROUP BY vs OVER

Example

Each employee with their department's average salary next to them:

SELECT FirstName, Department, Salary,
       ROUND(AVG(Salary) OVER (PARTITION BY Department), 0) AS DeptAvg,
       Salary - ROUND(AVG(Salary) OVER (PARTITION BY Department), 0) AS DiffFromAvg
FROM Employees
ORDER BY Department, Salary DESC;

Result: 6 rows

FirstNameDepartmentSalaryDeptAvgDiffFromAvg
FatimaFinance80000800000
RahulSales72000636678333
DavidSales6100063667-2667
SaraSales5800063667-5667
JamesSupport670005600011000
AnanyaSupport4500056000-11000

Share of Total

Example

Each order as a percentage of all revenue:

SELECT OrderID, Amount,
       ROUND(100.0 * Amount / SUM(Amount) OVER (), 1) AS PctOfRevenue
FROM Orders
ORDER BY Amount DESC;

Result: 8 rows

OrderIDAmountPctOfRevenue
10341227.5
106320.7521.4
101245.516.4
108198.413.2
10515010
10289.96
10456.253.8
107271.8

OVER () with nothing inside makes the whole result one window.

Window Function Families

FamilyFunctions
AggregateSUM, AVG, COUNT, MIN, MAX with OVER
RankingROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK
Value / offsetLAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUE