带分页的有序联合查询

时间:2014-12-07 17:53:07

标签: sql-server pagination

对于一个查询,这个工作正常:

SELECT * 
FROM  
   ( SELECT ROW_NUMBER() OVER (ORDER BY id_article DESC) AS RowNum, 
            id_article, 
            article_name, ... 
     FROM articles 
) AS  RowConstrainedResult  
WHERE RowNum >=0 
      AND 
      RowNum <= 20 
ORDER BY  RowNum

现在我需要第一个查询与同一个表中的另一个查询按日期和分页结果排序。

SELECT  articles.id_article AS ID, 
        articles.article_name AS NAME,
        articles.article_dateNew AS DATE 
FROM articles 
UNION 
SELECT  free_arts.id_art AS ID, 
        free_arts.art_name AS NAME, 
        free_arts.art_dateNew AS DATE 
FROM free_arts 
ORDER BY DATE DESC

1 个答案:

答案 0 :(得分:0)

SELECT * 
FROM  
(
     Select V1.* , ROW_NUMBER() OVER (ORDER BY DATE DESC) AS RowNum
     From
       (
          SELECT  articles.id_article AS ID, 
                  articles.article_name AS NAME,
                  articles.article_dateNew AS DATE 
          FROM articles 
          UNION -- All
          SELECT free_arts.id_art AS ID, 
                 free_arts.art_name AS NAME, 
                 free_arts.art_dateNew AS DATE 
          FROM free_arts               
        ) as V1           
  )
WHERE RowNum >=0 
      AND
      RowNum <= 20 
--ORDER BY  RowNum