SQLite 排名函数实测:并列名次、跳号与稳定序号
同样一份排行榜,前三行、前三名和前三档分数可能是三种结果。本文用虚构关卡榜说明 SQLite 的 ROW_NUMBER、RANK 与 DENSE_RANK:先决定是否保留并列,再决定如何稳定展示,不能只把函数名换一遍就认为语义相同。示例只创建内存数据库,不连接业务库,也不涉及真实人员或资金决策。

先看同分时怎样编号
A 组前四项分数是 100、100、90、80。以分数降序排名,RANK 得到 1、1、3、4:下一组名次相当于它在有序列表中的起始位置。DENSE_RANK 得到 1、1、2、3,只按不同分数组计数。ROW_NUMBER 则逐行给出 1、2、3、4,不产生共享序号。它适合选定数量的行,却不能直接表达同分同名次。三者的定义见 SQLite 官方窗口函数文档。
唯一编号应该放在哪个窗口
这里的 peers 指同一分区内,窗口 ORDER BY 全部表达式取值相同的行。如果原来只按 score 排名,再加入唯一 id,两项 100 分也不再属于同一同位组,RANK 和 DENSE_RANK 就都会变成不同名次。这不是稳定化的无害补丁,而是改变了并列标准。
完整脚本因此定义两个命名窗口:w_pos 用分数和唯一 id,为 ROW_NUMBER 提供明确的平局顺序;w_score 只用分数,保留共享名次。仅按分数执行 ROW_NUMBER 时,不要依赖同分行恰巧呈现的顺序。稳定序号指相同数据与完整排序规则下的可复现结果,并不保证数据新增后序号永远不变。第 6 组还验证省略窗口排序的情况:所有行都算同位,两个排名函数都返回一,行号则仍各不相同。
分组、空值和展示分别处理
PARTITION BY division 让 A、B 两组独立从头编号;删除它就变成全榜排名。窗口内的 ORDER BY 决定计算顺序,最外层 ORDER BY 决定展示顺序。第 7 组故意倒序展示 id,已有名次不会被倒着重算。没有外层排序时,不应把观察到的返回顺序当作保证,详见 SELECT 排序规则。
示例把缺失成绩保留在榜内,并显式写出 DESC NULLS LAST;两个 NULL 在分数窗口内共享末尾名次,但位置窗口仍靠 id 区分。真实需求若规定未计分项目不参榜,应在排名前排除,而不是把 NULL 默认为零。本例使用该排序语法,因此要求 SQLite 3.30.0 或更新版本,语法加入时间见 官方发布说明。
先筛选还是先排名
第 8 组先留下 id 为 2 到 4 的三项,再排名,结果为 1、2、3;第 9 组先排完整榜,再在外层挑出相同行,保留 1、3、4。两者回答的问题分别是“子集内部第几”和“这些项目原本第几”。要按窗口计算出的名次筛选,用公共表表达式或子查询分两层写,别在同层 WHERE 中引用窗口结果。
第 10 组进一步检查榜单截取:取一行只返回 id=1,取第一名会保留 id=1、2;取前两档分数还会包含 id=3。选择条件之前,先把“前几名”转成明确的业务定义。
可直接运行的十二组检查
将下方代码保存为 test_sqlite_rank.py,分别运行 python test_sqlite_rank.py 与 python -O test_sqlite_rank.py。本次实测为 CPython 3.12.14、SQLite 3.53.1,两次均通过 12 组检查。check 使用显式条件和异常,不依赖会被优化模式移除的 assert 语句。sqlite3 的内存连接、参数绑定与运行库版本接口可查 Python 官方文档。以下是语义验证,不是性能基准。
import platform
import sqlite3
import sys
def check(name, actual, expected):
if actual != expected:
raise AssertionError(f'{name}: {actual!r} != {expected!r}')
print(f'PASS {name}')
print(f'{platform.python_implementation()} {platform.python_version()} | '
f'SQLite {sqlite3.sqlite_version} | optimize={sys.flags.optimize}')
if sqlite3.sqlite_version_info < (3, 30, 0):
raise RuntimeError('This example requires SQLite 3.30.0 or newer.')
con = sqlite3.connect(':memory:')
try:
con.execute('''CREATE TABLE board (
id INTEGER PRIMARY KEY,
division TEXT NOT NULL,
score INTEGER
)''')
con.executemany('INSERT INTO board VALUES (?, ?, ?)', [
(1, 'A', 100), (2, 'A', 100), (3, 'A', 90),
(4, 'A', 80), (5, 'A', None), (6, 'A', None),
(7, 'B', 100), (8, 'B', 70), (9, 'B', 70),
])
def rows(sql, params=()):
return con.execute(sql, params).fetchall()
# Separate windows: stable position and shared score rank.
ranked = '''WITH ranked AS (
SELECT id, division, score,
ROW_NUMBER() OVER w_pos AS pos,
RANK() OVER w_score AS rk,
DENSE_RANK() OVER w_score AS dr
FROM board
WINDOW w_pos AS (
PARTITION BY division
ORDER BY score DESC NULLS LAST, id
), w_score AS (
PARTITION BY division
ORDER BY score DESC NULLS LAST
)
) '''
check('01 row_number assigns distinct positions', rows(ranked + '''
SELECT id, pos FROM ranked WHERE id <= 4 ORDER BY id
'''), [(1, 1), (2, 2), (3, 3), (4, 4)])
check('02 rank leaves gaps after ties', rows(ranked + '''
SELECT id, rk FROM ranked WHERE id <= 4 ORDER BY id
'''), [(1, 1), (2, 1), (3, 3), (4, 4)])
check('03 dense_rank counts peer groups', rows(ranked + '''
SELECT id, dr FROM ranked WHERE id <= 4 ORDER BY id
'''), [(1, 1), (2, 1), (3, 2), (4, 3)])
check('04 partitions restart independently', rows(ranked + '''
SELECT id, pos, rk, dr FROM ranked
WHERE division = 'B' ORDER BY id
'''), [(7, 1, 1, 1), (8, 2, 2, 2), (9, 3, 2, 2)])
check('05 unique id destroys score ties', rows('''
SELECT id, RANK() OVER w, DENSE_RANK() OVER w
FROM board WHERE id <= 4
WINDOW w AS (ORDER BY score DESC NULLS LAST, id)
ORDER BY id
'''), [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4)])
no_order = rows('''
SELECT ROW_NUMBER() OVER (), RANK() OVER (),
DENSE_RANK() OVER () FROM board WHERE id <= 4
''')
# No assumption about which id receives each row number.
check('06 no window order makes all rows peers',
sorted(no_order), [(1, 1, 1), (2, 1, 1),
(3, 1, 1), (4, 1, 1)])
check('07 outer order changes display not ranks', rows(ranked + '''
SELECT id, pos, rk FROM ranked
WHERE id <= 4 ORDER BY id DESC
'''), [(4, 4, 4), (3, 3, 3), (2, 2, 1), (1, 1, 1)])
check('08 filter before ranking changes population', rows('''
SELECT id, RANK() OVER (ORDER BY score DESC NULLS LAST)
FROM board WHERE id BETWEEN 2 AND 4 ORDER BY id
'''), [(2, 1), (3, 2), (4, 3)])
check('09 filter after ranking preserves original ranks',
rows(ranked + '''
SELECT id, rk FROM ranked
WHERE id BETWEEN 2 AND 4 ORDER BY id
'''), [(2, 1), (3, 3), (4, 4)])
top_sets = []
for n in (1, 2):
selections = []
# Column names are fixed trusted literals, not external input.
for column in ('pos', 'rk', 'dr'):
result = rows(ranked + f'''
SELECT id FROM ranked
WHERE division = 'A' AND {column} <= ? ORDER BY id
''', (n,))
selections.append([item[0] for item in result])
top_sets.append(selections)
check('10 top positions ranks and score tiers differ', top_sets,
[[[1], [1, 2], [1, 2]],
[[1, 2], [1, 2], [1, 2, 3]]])
check('11 explicit nulls last keeps null scores together',
rows(ranked + '''
SELECT id, pos, rk, dr FROM ranked
WHERE score IS NULL ORDER BY id
'''), [(5, 5, 5, 4), (6, 6, 5, 4)])
check('12 without partition all divisions compete', rows('''
SELECT id, RANK() OVER (ORDER BY score DESC NULLS LAST)
FROM board ORDER BY id
'''), [(1, 1), (2, 1), (3, 4), (4, 5), (5, 8),
(6, 8), (7, 1), (8, 6), (9, 6)])
print('12 groups passed; only the in-memory database was used.')
finally:
con.close() 
