Careeroza
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
| FirstName | Department | Salary | DeptAvg | DiffFromAvg |
|---|---|---|---|---|
| Fatima | Finance | 80000 | 80000 | 0 |
| Rahul | Sales | 72000 | 63667 | 8333 |
| David | Sales | 61000 | 63667 | -2667 |
| Sara | Sales | 58000 | 63667 | -5667 |
| James | Support | 67000 | 56000 | 11000 |
| Ananya | Support | 45000 | 56000 | -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
| OrderID | Amount | PctOfRevenue |
|---|---|---|
| 103 | 412 | 27.5 |
| 106 | 320.75 | 21.4 |
| 101 | 245.5 | 16.4 |
| 108 | 198.4 | 13.2 |
| 105 | 150 | 10 |
| 102 | 89.9 | 6 |
| 104 | 56.25 | 3.8 |
| 107 | 27 | 1.8 |
OVER () with nothing inside makes the whole result one window.
Window Function Families
| Family | Functions |
|---|---|
| Aggregate | SUM, AVG, COUNT, MIN, MAX with OVER |
| Ranking | ROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK |
| Value / offset | LAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUE |