语法格式:row_number() over(partition by 分组列 order by 排序列 desc)
row_number() over()分组排序功能:
在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where 、group by,但不晚于 order by 的执行。
案例
表数据
createtableTEST_ROW_NUMBER_OVER( idvarchar(10) notnull, namevarchar(10) null, agevarchar(10) null, salaryintnull); select*fromTEST_ROW_NUMBER_OVERt; insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a',10,8000); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a2',11,6500); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b',12,13000); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b2',13,4500); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c',14,3000); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c2',15,20000); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(4,'d',16,30000); insertintoTEST_ROW_NUMBER_OVER(id,name,age,salary) values(5,'d2',17,1800);
一次排序:对查询结果进行排序(无分组)
selectid,name,age,salary,row_number()over(orderbysalarydesc) rnfromTEST_ROW_NUMBER_OVERt
结果
进一步排序:根据id分组排序
selectid,name,age,salary,row_number()over(partitionbyidorderbysalarydesc) rankfromTEST_ROW_NUMBER_OVERt
结果
再一次排序:找出每一组中序号为一的数据
select*from(selectid,name,age,salary,row_number()over(partitionbyidorderbysalarydesc) rankfromTEST_ROW_NUMBER_OVERt) whererank<2
结果
排序找出年龄在13岁到16岁数据,按salary排序
selectid,name,age,salary,row_number()over(orderbysalarydesc) rankfromTEST_ROW_NUMBER_OVERtwhereagebetween'13'and'16'
结果:结果中 rank 的序号,其实就表明了 over(order by salary desc) 是在where age between and 后执行的