我的应用程序使用常规格式执行许多查询:
SELECT <aggregate-functions>
FROM <table-name>
WHERE <where-clause>
GROUP BY <group-by column list>
我想知道有多少记录贡献给聚合结果集(换句话说,有多少记录符合WHERE子句中的条件),这是由于SELECT子句中的聚合函数和GROUP-BY子句。我知道我可以使用相同的WHERE子句来做一个简单的SELECT COUNT(*)来获取该数字,但是如果可能的话我想避免第二个查询。是否有SQL Server功能/功能/等将产生该值而无需另一个查询?
答案 0 :(得分:1)
一个简单的解决方案是子选择:
Select ...
, ( Select Count(*)
From Table
Where ...) As TotalCount
From Table
Where ...
Group By ...
如果您使用的是SQL Server 2005或更高版本,则可以执行以下操作:
With RankedItems As
(
Select Col1
, Row_Number() Over ( Order By Col1 Asc, Col2 Asc... ) As Num
, Row_Number() Over ( Order By Col1 Desc, Col2 Desc ) As RevNum
From Table
Where ...
)
Select Col1, Min(Num + RevNum - 1) As TotalCount
From RankedItems
Group By Col1
答案 1 :(得分:1)
您可以为某个涉及聚合的任意值添加计数,甚至可以添加
SELECT x.name,
y.name,
z.name,
AVG(x.tacos) AS average_tacos,
SUM(1) AS aggregated_row_count
FROM ....
WHERE ...
GROUP BY x.name, y.name, z.name