语法:row_number() over(partition by column order by column)
简单的说row_number()
从1开始,为每一条分组记录返回一个数字,这里的row_number() over (order by cylh desc)
是先把xlh列降序,再为降序以后的每条cylh记录返回一个序号。
示例:
分析:row_number() over (partition by col1 order by col2)
表示根据col1分组,在分组内部根据 col2
排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)
也可这样使用:row_number() over (order by col2)
例子:
建立测试表,并插入测试数据
1
2
3
4
5
|
create table test_row_number_01( cmzh varchar (10) not null , cylh varchar (10) null , mje money null , ); |
1
2
3
4
5
6
7
8
9
10
|
insert into test_row_number_01(cmzh,cylh,mje) values (2106000011,20281997,10.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000010,20281996,10.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000008,20281995,0.00) insert into test_row_number_01(cmzh,cylh,mje) values (2106000006,20281994,9.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000004,20281993,5.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000001,20281992,10.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000002,20281992,10.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000007,20217280,0.00) insert into test_row_number_01(cmzh,cylh,mje) values (2106000009,20172458,5.50) insert into test_row_number_01(cmzh,cylh,mje) values (2106000005,20121813,0.00) |
执行脚本自动生成行号并按cylh进行排序(滑动查看代码)
1
|
select row_number()over( order by cylh desc ) as rownum,* from test_row_number_01 |
结果如下:
注意:在使用over
等开窗函数时,over
里头的分组及排序的执行晚于“where
,group by
,order by
”的执行。
到此这篇关于sql使用row_number() over函数生成序列号的文章就介绍到这了,更多相关sql用row_number() over生成序列号内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/since-1995/p/15629029.html