語法格式:row_number() over(partition by 分組列 order by 排序列 desc)
一個很簡單的例子
1,先做好准備
create table test1( id varchar(4) not null, name varchar(10) null, age varchar(10) null ); select * from test1; insert into test1(id,name,age) values(1,'a',10); insert into test1(id,name,age) values(1,'a2',11); insert into test1(id,name,age) values(2,'b',12); insert into test1(id,name,age) values(2,'b2',13); insert into test1(id,name,age) values(3,'c',14); insert into test1(id,name,age) values(3,'c2',15); insert into test1(id,name,age) values(4,'d',16); insert into test1(id,name,age) values(5,'d2',17);
2,開始使用之~
select t.id, t.name, t.age, row_number() over(partition by t.id order by t.age asc) rn from test1 t
結果:
id name age rn
1 a 10 1
1 a2 11 2
2 b 12 1
2 b2 13 2
3 c 14 1
3 c2 15 2
4 d 16 1
5 d2 17 1
3,進一步排序
select * from (select t.id, t.name, t.age, row_number() over(partition by t.id order by t.age asc) rn from test1 t) where rn < 2
結果:
id name age rn
1 a 10 1
2 b 12 1
3 c 14 1
4 d 16 1
5 d2 17 1
4,總結
工作半年的經驗來看,基本上row_number() over()這個函數主要用在各種數據統計的sql中,感覺比group by好用的都,可以在一個查詢中對多列數據進行分組,尤其在多表關聯查詢中,row_number() over()還是非常便捷的。