Sqlserver中Row_Number的使用场景
一、 例子集合
首先展示举例的数据集合,并给每条记录标上一个行号
SELECT ROW_NUMBER() over (order by creatime) as num
,[name]
,[creatime]
,[count]
FROM [TEST].[dbo].[Table_1]

二、 分页
由于每条记录可以添加行号,也就从而实现了分页。此处,提取每页大小为3,页号为3的记录:
declare @pageNum int
declare @pageSize int
set @pageNum = 3
set @pageSize = 3
select [name]
,[creatime]
,[count]
FROM(SELECT ROW_NUMBER() over (order by creatime) as num
,[name]
,[creatime]
,[count]
FROM [TEST].[dbo].[Table_1]) as tempT
where (@pageNum - 1)* @pageSize < num and num <= @pageNum * @pageSize

三、 分组并排序
实现分组,并显示出每组数据。如下,将name进行分组,并每组按creatime排序
SELECT ROW_NUMBER() over (PARTITION by name order by creatime) as num
,[name]
,[creatime]
,[count]
FROM [TEST].[dbo].[Table_1]

四、 分组里的最后一条数据
实现分组,并显示出每组数据的最后一条数据。如下,将name进行分组,并显示creatime排序的最后一条数据。
select [name]
,[creatime]
,[count]
FROM(SELECT ROW_NUMBER() over (PARTITION by name order by creatime desc) as num
,[name]
,[creatime]
,[count]
FROM [TEST].[dbo].[Table_1]) as tempT
where num = 1

版权声明:本文为weixin_41703489原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。