Example 1
Rank reps and show the previous rep's revenue using a shared window
WINDOW w AS (PARTITION BY region ORDER BY revenue DESC) defines the window once. Both RANK() OVER w and LAG(revenue) OVER w reference it without repeating the specification. Within the East region Alice ranks first (no previous row, so LAG returns NULL), Eve ranks second with 85000 as the previous revenue, and Bob ranks third with 79000. Within West, Carol ranks first and Dave ranks second with 91000 as the previous revenue. SQL Server achieves the same result but requires the OVER clause to be written out in full for each function.
CREATE TABLE sales_reps (name VARCHAR(50), region VARCHAR(20), revenue INT);
INSERT INTO
sales_reps
VALUES
('Alice', 'East', 85000),
('Bob', 'East', 72000),
('Carol', 'West', 91000),
('Dave', 'West', 68000),
('Eve', 'East', 79000);SELECT
name,
region,
revenue,
RANK() OVER w AS rnk,
LAG (revenue) OVER w AS prev_revenue
FROM
sales_reps
WINDOW
w AS (
PARTITION BY
region
ORDER BY
revenue DESC
)
ORDER BY
region,
rnk;| name | region | revenue | rnk | prev_revenue |
|---|---|---|---|---|
| Alice | East | 85000 | 1 | NULL |
| Eve | East | 79000 | 2 | 85000 |
| Bob | East | 72000 | 3 | 79000 |
| Carol | West | 91000 | 1 | NULL |
| Dave | West | 68000 | 2 | 91000 |
CREATE TABLE sales_reps (name VARCHAR(50), region VARCHAR(20), revenue INT);
INSERT INTO
sales_reps
VALUES
('Alice', 'East', 85000),
('Bob', 'East', 72000),
('Carol', 'West', 91000),
('Dave', 'West', 68000),
('Eve', 'East', 79000);SELECT
name,
region,
revenue,
RANK() OVER (
PARTITION BY
region
ORDER BY
revenue DESC
) AS rnk,
LAG (revenue) OVER (
PARTITION BY
region
ORDER BY
revenue DESC
) AS prev_revenue
FROM
sales_reps
ORDER BY
region,
rnk;| name | region | revenue | rnk | prev_revenue |
|---|---|---|---|---|
| Alice | East | 85000 | 1 | NULL |
| Eve | East | 79000 | 2 | 85000 |
| Bob | East | 72000 | 3 | 79000 |
| Carol | West | 91000 | 1 | NULL |
| Dave | West | 68000 | 2 | 91000 |
MySQL, MariaDB, PostgreSQL, and SQLite define the window with `WINDOW w AS (...)` and reference it with `OVER w`. SQL Server must repeat the full `OVER (PARTITION BY region ORDER BY revenue DESC)` on each function.