分页SQL Server结果

时间:2014-08-18 10:39:04

标签: sql sql-server

我有两个表,OrdersArticles。我希望ordersarticles位于同一结果集中,按[DateCreated]排序。我需要分页,所以我使用WITH。下面的查询存在的问题是,[RowNumber]是每个查询的单独计数器。

不是在以下查询中获得10行,而是获得20.有关如何解决此问题的任何想法?

我需要一个包含整个WITH子句的计数器。

查询:

;WITH MySelectedRows AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [DateCreated] DESC) as [RowNumber]
    , [ArticleID]     as [ID]
    , [DateCreated]   as [Date]
    , [ArticleText]   as [Text]
    , 'Articles'      as [RowType]
    FROM Articles

    UNION

    SELECT ROW_NUMBER() OVER (ORDER BY [DateCreated] DESC) as [RowNumber]
    , [OrderID]       as [ID]
    , [DateCreated]   as [Date]
    , [OrderText]     as [Text]
    , 'Orders'        as [RowType]
    FROM Orders
)
SELECT [ID], [Date], [Text], [RowType] FROM MySelectedRows
WHERE [RowNumber] BETWEEN 1 and 10

1 个答案:

答案 0 :(得分:1)

您需要在组合结果集上获取行号,而不是在每个查询中获取行号。因此,您可以将联合包装在CTE /子查询中,然后应用ROW_NUMBER并执行分页,如下所示:

;with cte as
(
 SELECT
, [ArticleID]     as [ID]
, [DateCreated]   as [Date]
, [ArticleText]   as [Text]
, 'Articles'      as [RowType]
FROM Articles

UNION

SELECT
, [OrderID]       as [ID]
, [DateCreated]   as [Date]
, [OrderText]     as [Text]
, 'Orders'        as [RowType]
FROM Orders
),

ordered as
(
 select
 *
 ,ROW_NUMBER() OVER (ORDER BY [Date] DESC) as [RowNumber]
from cte
)

select * from ordered
where RowNumber between 1 and 10