Window Functions
Window Functions
Functions
crash course
Swipe 👉👉👉
Window functions in SQL are a powerful feature
that allows performing calculations across a set
of table rows related to the current row, but
without grouping the rows into a single output
row, as aggregation functions do. Instead, they
maintain row-wise results.
SELECT
employee_id,
department_id,
salary,
ROW_NUMBER() OVER(PARTITION BY
department_id ORDER BY salary DESC) AS
row_num
FROM
employees;
SELECT
employee_id,
department_id,
salary,
RANK() OVER(PARTITION BY
department_id ORDER BY salary DESC) AS
rank
FROM
employees;
SELECT
employee_id,
department_id,
salary,
DENSE_RANK() OVER(PARTITION BY
department_id ORDER BY salary DESC) AS
dense_rank
FROM
employees;
SELECT
employee_id,
department_id,
salary,
PERCENT_RANK() OVER(PARTITION BY
department_id ORDER BY salary DESC) AS
percent_rank
FROM
employees;
SELECT
employee_id,
department_id,
salary,
LAG(salary, 1) OVER(PARTITION BY
department_id ORDER BY salary) AS
previous_salary
FROM
employees;
SELECT
employee_id,
department_id,
salary,
LEAD(salary, 1) OVER(PARTITION BY
department_id ORDER BY salary) AS
next_salary
FROM
employees;