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;
| name | department_id | salary | salary_rank |
|---|---|---|---|
| Ana Costa | 1 | 168000 | 1 |
| Ben Okafor | 2 | 152000 | 1 |
| Farid Haddad | 2 | 132000 | 2 |
| Xenia Petrova | 2 | 125000 | 3 |
| Grace Liu | 2 | 112000 | 4 |
| Hannes Berg | 2 | 109000 | 5 |
| Isla Reid | 2 | 86000 | 6 |
| Vera Popescu | 2 | 84000 | 7 |
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.