计算查询中的总行数

时间:2012-06-12 12:58:44

标签: c# asp.net sql sql-server-2008 ibatis

我有一个SqlServer SELECT

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

,我如何知道行的总数

3 个答案:

答案 0 :(得分:4)

使用反行技巧

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

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

答案 1 :(得分: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

答案 2 :(得分: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