我有一个 SQL Server 2008 查询
SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...
我还想获得总行数。obious的方法是进行第二次查询
SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...
有没有有效的方法?
谢谢
我有一个 SQL Server 2008 查询
SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...
我还想获得总行数。obious的方法是进行第二次查询
SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...
有没有有效的方法?
谢谢
你想要第二个查询吗?
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
...
这个答案中的内容似乎有效:
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.
也从第二个查询中删除 ORDER BY 子句。
不。
SQL Server
不保存COUNT(*)
在元数据中MyISAM
,它每次都计算它。
更新:如果您需要估算,可以使用统计元数据:
SELECT rows
FROM dbo.sysindexes
WHERE name = @primary_key,
@primary_key
您的表的主键名称在哪里。
这将返回COUNT(*)
上次统计更新的数据。
SELECT TOP (2) *,
(SELECT COUNT(*) AS Expr1 FROM T) AS C
FROM T