Filter Window Output Via Subquery

Window functions evaluate after WHERE, so filtering on row_number output requires numbering rows in a CTE first, then selecting rn = 1 outside.

SqlData Fetching

Code

snippet
WITH employees(dept, name, salary) AS (
    VALUES
        ('infra', 'ada', 4200),
        ('infra', 'kim', 3800),
        ('infra', 'raj', 3800),
        ('web',   'mei', 3300),
        ('web',   'zoe', 2900)
),
-- 第一步:在子查询/CTE 里编号
ranked AS (
    SELECT
        dept, name, salary,
        ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
    FROM employees
)
-- 第二步:在外层过滤窗口输出
SELECT dept, name, salary
FROM ranked
WHERE rn = 1
ORDER BY dept;
-- 直接写 WHERE ROW_NUMBER() OVER (...) = 1 会报错:
-- ERROR:  window functions are not allowed in WHERE
-- 窗口函数在 WHERE 过滤完行之后才求值,只能先编号再过滤。
-- 并列最高时 ROW_NUMBER 只取其一;要并列全取改用 RANK() <= 1 或 DISTINCT ON。

Inside the snippet

At its core this is a single SELECT statement against employees and ranked.

The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause that limits which rows the statement affects; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Caveats

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

The employees table is the working surface here.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`employees`, `ranked`.