计算与分页联合的所有行(OFFSET,FETCH)

时间:2017-11-03 09:47:17

标签: sql sql-server tsql stored-procedures

这是我的查询。

 SELECT 
         S.Id,
         S.[Order],
         COUNT(*) OVER () AS Total_Count --Return 4
FROM Subscriptions S
UNION 
SELECT 
         S1.Id,
         S1.[Order],
         COUNT(*) OVER () AS Total_Count --return 5
FROM Subscriptions1 S1
ORDER BY [Order] DESC
            OFFSET 0 ROWS 
    FETCH NEXT 2 ROWS ONLY

我想要的是每排9(4 + 5)。

1 个答案:

答案 0 :(得分:3)

使用子查询:

SELECT id, [Order], COUNT(*) OVER () AS Total_Count
FROM ((SELECT S.Id, S.[Order],
       FROM Subscriptions S
      ) UNION 
      (SELECT S1.Id, S1.[Order]
       FROM Subscriptions1 S1
      )
     ) s
ORDER BY [Order] DESC
OFFSET 0 ROWS 
FETCH NEXT 2 ROWS ONLY;

注意:如果您想要产生删除重复项的开销,请仅使用UNION。否则,请使用UNION ALL