Search code examples
sql-serveraggregaterecord-count

Get number of records scanned in aggregate query


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?


Solution

  • 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