如何使用rownumber在SQL中编写分页查询

时间:2013-06-30 15:30:36

标签: sql sql-server

我知道如何使用“select top”来编写分页查询,但我不知道如何使用rownumber编写它。 谁能告诉我?谢谢!

2 个答案:

答案 0 :(得分:5)

select * from (
    select ROW_NUMBER() over (order by SalesOrderDate desc) as rn, *
    from sales.salesorderheader
) as x
where rn between @start and @start + @page_size

应该这样做。

答案 1 :(得分:-2)

尝试以下概括查询:

DECLARE @Start INT = 0
DECLARE @page_size INT = 10
DECLARE @Orderby VARCHAR(max) = 'SalesOrderDate'
DECLARE @Order VARCHAR(max) = 'desc';

WITH temp
     AS (SELECT case when 'SalesOrderDate' then ROW_NUMBER() OVER (ORDER BY SalesOrderDate) 
                                            ELSE ROW_NUMBER() OVER (ORDER BY id) END AS rn,
                *
         FROM   sales.salesorderheader)
SELECT *
FROM   (SELECT row_number() OVER(ORDER BY CASE 
                                          WHEN @Order = 'asc' 
                                          THEN rn 
                                          ELSE -rn 
                                          END) AS finalorder,
               *
        FROM   temp) AS x
WHERE  finalorder BETWEEN @start AND @start + @page_size