背景: sql
在分页功能中,记录需分页显示,须要row_number()函数标记行号。函数
数据表:.net
排序以前数据表显示:blog
sql语句:排序
1 select ROW_NUMBER() over(order by id) as RowNum,Name,Val from T1
检索结果:get
注意:Leslie的ID为Null,通过排序以后,rows却升为了首位。it
常见错误:列名RowNum失效。select
解释:在sql中热名称(即刚定的名称RowNum)不能立刻使用,须要包一层查询。
好比说:实现分页显示,只想查询1-5行的结果,sql语句以下:sql语句
1 select ROW_NUMBER() over(order by id) as rows,Name,Val from T1 where rows between 1 and 5
解决方案:分页
1 select * from 2 (select ROW_NUMBER() over(order by id) as rows,Name,Val from T1) U 3 where rows between 1 and 5;
也就是:
1 with A as 2 ( 3 select ROW_NUMBER() over(order by id) as rows,Name,Val from T1 4 ) 5 select * from A where A.rows between 1 and 5;
检索结果:
参考资料:热名称
在某些状况下,咱们但愿指定RowNum的排序方式,好比把热门城市(如北京、上海等)排在靠前的位置。
这时须要组合case...when...then的方式来使用Row_Number()函数。sql语句以下:
1 select ROW_NUMBER() over( 2 order by 3 case Name 4 when 'Leslie' then 1 5 when 'Lily' then 2 6 else 3 end asc)as RowNum,Name,Val from T1
检索结果以下: