All SQL topics
SQL TOPIC

SQL window functions: running totals, ranks and month-over-month

Window functions calculate across related rows without collapsing them: rankings, running totals, previous month.

SUM(revenue) OVER (ORDER BY month) gives a running total. RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) ranks within each department.

LAG(revenue) OVER (ORDER BY month) returns last month's value on the same row, which makes growth calculations simple.

Worked example

Rank employees by salary within their department.

SELECT name, department_id, salary,
  RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees
ORDER BY department_id, salary_rank
LIMIT 8;
Result on the sample data
namedepartment_idsalarysalary_rank
Ana Costa11680001
Ben Okafor21520001
Farid Haddad21320002
Xenia Petrova21250003
Grace Liu21120004
Hannes Berg21090005
Isla Reid2860006
Vera Popescu2840007

Common mistakes

  • Filtering on a window result in WHERE: wrap the query in a CTE first.
  • Leaving out PARTITION BY and ranking across the whole company.