1

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

4

2 回答 2

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

这应该可以解决问题。

于 2013-06-30T15:34:48.820 回答
-3

尝试以下泛化查询:

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 
于 2013-06-30T15:43:01.303 回答