Union All使用不同的排序和分页将两个表组合在一起

时间:2014-12-24 15:43:30

标签: sql-server

我正在使用MS-SQL 2012,并且有2个包含类似数据字段类型的表。

我正在编写一个存储过程,需要使用特定排序顺序从Table1获取10条记录,使用不同排序顺序从Table2获取10条记录。

我还需要使用分页

这样的东西
SELECT Field1, Field2, Field3   
  FROM TableAAAA  
ORDER BY FieldSort1 DESC    --> DateTime
OFFSET (@PageIndex-1) * 10 ROWS   
  FETCH NEXT @PageSize ROWS ONLY  

UNION ALL

SELECT Field1, Field2, Field3   
  FROM TableBBBB   
ORDER BY FieldSort2    --> INT
OFFSET (@PageIndex-1) * 10 ROWS   
  FETCH NEXT @PageSize ROWS ONLY  

如果我使用UNION ALL,我只能在它的末尾排序,所以我不能使用上面的代码。

2 个答案:

答案 0 :(得分:3)

这是一种方式(因为你知道第一个只是页面大小...

WITH t1 AS
(

  SELECT Field1, Field2, Field3, ROW_NUMBER() OVER (ORDER BY FieldSort1) AS outerSort1, 0 as outerSort2
  FROM TableAAAA  
  ORDER BY FieldSort1
  OFFSET (@PageIndex-1) * 10 ROWS   
    FETCH NEXT @PageSize ROWS ONLY  
), t2 AS
(
  SELECT Field1, Field2, Field3, 0 as outerSort1, ROW_NUMBER() OVER (ORDER BY FieldSort2) AS outerSort2   
  FROM TableBBBB   
  ORDER BY FieldSort2
  OFFSET (@PageIndex-1) * 10 ROWS   
    FETCH NEXT @PageSize ROWS ONLY  
)
SELECT Field1, Field2, Field3 FROM T1
UNION ALL
SELECT Field1, Field2, Field3 FROM T2
ORDER BY outerSort1, outerSort2

答案 1 :(得分:2)

您可以使用派生表或CTE:

WITH cteA AS (
SELECT Field1, Field2, Field3
  FROM TableAAAA  
ORDER BY FieldSort1
OFFSET (@PageIndex-1) * 10 ROWS   
  FETCH NEXT @PageSize ROWS ONLY  
),
cteB AS (
SELECT Field1, Field2, Field3
  FROM TableBBBB   
ORDER BY FieldSort2
OFFSET (@PageIndex-1) * 10 ROWS   
  FETCH NEXT @PageSize ROWS ONLY  
)
SELECT * FROM cteA
UNION ALL
SELECT * FROM cteB