Window Functions for Analytics
Uses window functions like ROW_NUMBER, RANK, LAG, LEAD, and running totals to perform advanced analytics without collapsing result rows.
Code
SELECT
employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_rank,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS dept_rank,
LAG(salary, 1) OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS prev_salary,
LEAD(salary, 1) OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS next_salary,
SUM(salary) OVER (
PARTITION BY department_id
ORDER BY salary DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM employees
ORDER BY department_id, salary DESC;How the snippet works
At its core this is a single SELECT statement against employees.
Mechanically, the statements are built from: SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Watch out for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Run the statement against the employees table.
FAQ
- Name the tables involved in this file.
- The references are `employees`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.