2014-12-07 65 views
0

對於一個查詢這一個有序的聯合查詢工作正常:與分頁

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 

回答

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 
+0

感謝評論,但現在它返回一個錯誤:ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式無效,除非TOP或FOR XML也指定。 – 2014-12-08 08:16:49

+0

歡迎來到維基百科。我更新了我的答案,可能會派上用場。您可以將訂購邏輯轉移到ROW_NUMBER()OVER(ORDER BY ...) – 2014-12-08 08:56:32

+0

再次,非常感謝! – 2014-12-08 09:12:46