- 类别:
窗口函数 (排名相关、窗口框架)
DENSE_RANK¶
返回一组值中某个值的排名,排名中没有间隔。
排名值从 1 开始,并按顺序继续增加。
如果两个值相同,则它们具有相同的排名。
语法¶
DENSE_RANK() OVER ( [ PARTITION BY <expr1> ] ORDER BY <expr2> [ ASC | DESC ] [ <window_frame> ] )
有关 window_frame
语法的详细信息,请参阅 窗口框架语法和用法。
实参¶
无。
函数本身不接受任何实参,因为它返回窗口中当前行的排名(相对位置),该行按 <expr2>
排序。窗口的顺序决定了排名,因此无需向 RANK 函数传递额外的参数。
使用说明¶
示例¶
创建表和数据:
-- Create table and load data. create or replace table corn_production (farmer_ID INTEGER, state varchar, bushels float); insert into corn_production (farmer_ID, state, bushels) values (1, 'Iowa', 100), (2, 'Iowa', 110), (3, 'Kansas', 120), (4, 'Kansas', 130);
按降序显示农民的玉米产量,以及每个农民的产量排名(最高 = 1
):
SELECT state, bushels, RANK() OVER (ORDER BY bushels DESC), DENSE_RANK() OVER (ORDER BY bushels DESC) FROM corn_production; +--------+---------+-------------------------------------+-------------------------------------------+ | STATE | BUSHELS | RANK() OVER (ORDER BY BUSHELS DESC) | DENSE_RANK() OVER (ORDER BY BUSHELS DESC) | |--------+---------+-------------------------------------+-------------------------------------------| | Kansas | 130 | 1 | 1 | | Kansas | 120 | 2 | 2 | | Iowa | 110 | 3 | 3 | | Iowa | 100 | 4 | 4 | +--------+---------+-------------------------------------+-------------------------------------------+
在每个州内,按降序显示农民的玉米产量,以及每个农民的产量排名(最高 = 1
):
SELECT state, bushels, RANK() OVER (PARTITION BY state ORDER BY bushels DESC), DENSE_RANK() OVER (PARTITION BY state ORDER BY bushels DESC) FROM corn_production; +--------+---------+--------------------------------------------------------+--------------------------------------------------------------+ | STATE | BUSHELS | RANK() OVER (PARTITION BY STATE ORDER BY BUSHELS DESC) | DENSE_RANK() OVER (PARTITION BY STATE ORDER BY BUSHELS DESC) | |--------+---------+--------------------------------------------------------+--------------------------------------------------------------| | Iowa | 110 | 1 | 1 | | Iowa | 100 | 2 | 2 | | Kansas | 130 | 1 | 1 | | Kansas | 120 | 2 | 2 | +--------+---------+--------------------------------------------------------+--------------------------------------------------------------+
下面的查询和输出显示了 RANK() 和 DENSE_RANK() 函数如何处理平局值。请注意,对于 DENSE_RANK,排名是 1
、2
、3
、3
、4
。与 RANK() 函数的输出不同,不会跳过排名 4
,因为排名 3
是平局。
SELECT state, bushels, RANK() OVER (ORDER BY bushels DESC), DENSE_RANK() OVER (ORDER BY bushels DESC) FROM corn_production; +--------+---------+-------------------------------------+-------------------------------------------+ | STATE | BUSHELS | RANK() OVER (ORDER BY BUSHELS DESC) | DENSE_RANK() OVER (ORDER BY BUSHELS DESC) | |--------+---------+-------------------------------------+-------------------------------------------| | Kansas | 130 | 1 | 1 | | Kansas | 120 | 2 | 2 | | Iowa | 110 | 3 | 3 | | Iowa | 110 | 3 | 3 | | Iowa | 100 | 5 | 4 | +--------+---------+-------------------------------------+-------------------------------------------+