views:

18

answers:

2

My application performs a number of queries with the general form:

SELECT <aggregate-functions>
FROM <table-name>
WHERE <where-clause>
GROUP BY <group-by column list>

I would like to know how many records contributed to the aggregate result set (in other words, how many records matched the conditions in the WHERE clause), something that is hidden because of both both the aggregate functions in the SELECT clause and the GROUP-BY clause. I know that I could do a simple SELECT COUNT(*) using the same WHERE clause to get that number, but I would like to avoid a second query if at all possible. Is there a SQL Server feature/function/etc that will produce that value without another query?

+1  A: 

A simple solution would be a subselect:

Select ...
    , ( Select Count(*) 
        From Table 
        Where ...) As TotalCount
From Table
Where ...
Group By ...

If you are using SQL Server 2005 or later, you can do something like the following:

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
Thomas
Great, this does exactly what I want. Don't know why I didn't think of it.
Dan
+1  A: 

You can add in a count for some arbitrary value that's involved the aggregation, or even do

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
Jeremiah Peschka
This seems to work nicely, too. I'd just need to sum the aggregated_row_count column in the result set to get the total number of rows.
Dan