5

我有一个 SQL Server 2008 查询

SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...

我还想获得总行数。obious的方法是进行第二次查询

SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...

有没有有效的方法?

谢谢

4

5 回答 5

4

你想要第二个查询吗?

SELECT TOP 10
    *, foo.bar
FROM
    T
    CROSS JOIN
    (SELECT COUNT(*) AS bar FROM T WHERE ...) foo
WHERE
    ...
ORDER BY
    ...

或者

DECLARE @bar int
SELECT @bar = COUNT(*) AS bar FROM T WHERE ...
SELECT TOP 10
    *, @bar
FROM
    T
    CROSS JOIN
    (SELECT COUNT(*) AS bar FROM T WHERE ...) foo
WHERE
    ...
ORDER BY
    ...

或(编辑:使用 WITH)

WITH cTotal AS
(
    SELECT COUNT(*) AS bar FROM T WHERE ...)
)
SELECT TOP 10
    *, cTotal .bar
FROM
    T
WHERE
    ...
ORDER BY
    ...
于 2009-03-04T15:07:40.960 回答
4

这个答案中的内容似乎有效:

https://stackoverflow.com/a/19125458/16241

基本上你做一个:

SELECT top 100 YourColumns, TotalCount = Count(*) Over()
From YourTable
Where SomeValue = 32

TotalCount 将具有总行数。它虽然列在每一行。

When I tested this the query plan showed the table only being hit once.

于 2015-07-27T22:09:16.460 回答
1

也从第二个查询中删除 ORDER BY 子句。

于 2009-03-04T15:01:30.507 回答
1

不。

SQL Server不保存COUNT(*)在元数据中MyISAM,它每次都计算它。

更新:如果您需要估算,可以使用统计元数据:

SELECT  rows
FROM    dbo.sysindexes
WHERE   name = @primary_key,

@primary_key您的表的主键名称在哪里。

这将返回COUNT(*)上次统计更新的数据。

于 2009-03-04T15:03:27.710 回答
0
SELECT     TOP (2) *,
           (SELECT COUNT(*) AS Expr1 FROM T) AS C
FROM         T
于 2009-03-04T15:17:01.517 回答