1

我有一个 SqlServerSELECT

DECLARE @offset INT;
DECLARE @limit INT;

WITH cte
     AS (SELECT t.*,
                Row_number() OVER (ORDER BY Id) AS RowNum
         FROM   (SELECT *
                 FROM   Table1
                 UNION
                 SELECT *
                 FROM   Table2) t)
SELECT *
FROM   cte
WHERE  RowNum BETWEEN @offset AND @offset + @limit

如果没有 WHERE 条件,我如何知道限制的总行数RowNum BETWEEN @offset AND @offset + @limit

4

3 回答 3

4

使用逆行技巧

Row_number() OVER (ORDER BY Id asc) AS RowNum,
Row_number() OVER (ORDER BY Id desc) AS InverseRowNum,

然后 (RowNum + InverseRowNum) - 1 = 总行数

于 2012-06-12T13:03:46.190 回答
3

您可以将 count(*) over() 添加到 cte:

WITH cte
     AS (SELECT t.*,
                Row_number() OVER (ORDER BY Id) AS RowNum,
                count(*) over() as Cnt
         FROM   (SELECT *
                 FROM   Table1
                 UNION
                 SELECT *
                 FROM   Table2) t)
SELECT *
FROM   cte
WHERE  RowNum BETWEEN @offset AND @offset + @limit
于 2012-06-12T13:02:03.130 回答
0

将结果的计数视为另一个 CTE,并将其与记录集单独返回。不完美,但应该符合你想要的。

DECLARE @offset INT;
DECLARE @limit INT;

;WITH cte
 AS (SELECT t.*,
            Row_number() OVER (ORDER BY Id) AS RowNum
     FROM   (SELECT *
             FROM   Table1
             UNION
             SELECT *
             FROM   Table2) t)
, total_cte as (
       select count(1) total_count from cte
)
SELECT cte.*, total_count
FROM   cte, total_cte
WHERE  RowNum BETWEEN @offset AND @offset + @limit
于 2018-10-15T06:46:23.317 回答