实现说明
实际执行的是 SELECT / INSERT / CREATE——staff 是涉及的对象。
机制上由这些部分组成:窗口函数(OVER (…))对多行逐个求值,行不会被合并;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。
使用要点
- 窗口函数在
WHERE与GROUP BY之后求值——同级WHERE看不见它的输出。
常见问题
这段 SQL 会碰到哪些对象?
引用的是 staff。
核心语句
SELECT name, dept, score,
rank() OVER (PARTITION BY dept ORDER BY score DESC) AS dept_rank
FROM staff
ORDER BY dept, score DESC;
SELECT name, dept, score,
rank() OVER (ORDER BY score DESC) AS global_rank
FROM staff
ORDER BY score DESC;
INSERT INTO staff VALUES
('ada', 'dev', 92),
('raj', 'dev', 85),
('lin', 'ops', 90),
('kim', 'ops', 78);
代码示例
-- missing PARTITION BY: rank() spans the whole table
CREATE TABLE staff (
name text NOT NULL,
dept text NOT NULL,
score int NOT NULL
);
INSERT INTO staff VALUES
('ada', 'dev', 92),
('raj', 'dev', 85),
('lin', 'ops', 90),
('kim', 'ops', 78);
-- partition omitted: the 90 in ops still ranks behind the 85 in dev
SELECT name, dept, score,
rank() OVER (ORDER BY score DESC) AS global_rank
FROM staff
ORDER BY score DESC;
-- PARTITION BY added: ranking restarts inside each department
SELECT name, dept, score,
rank() OVER (PARTITION BY dept ORDER BY score DESC) AS dept_rank
FROM staff
ORDER BY dept, score DESC;