Search code examples
sqlsql-servert-sqlsql-server-2014

SELECT number of groups resulted from a GROUP BY query


I tried the following query to select the number of groups resulting from a GROUP BY query:

SELECT count(*)
FROM (
        SELECT count(*)
        FROM MyTable
        WHERE Col2 = 'x'
        GROUP BY Col1
     )

Unfortunately, this query is not valid: Incorrect syntax near ')'..

Note: I want to get exactly one row (I already found a solution with n times the result, where n = the group count).


Solution

  • SELECT count(*)
    FROM (
            SELECT 1 as dummy
            FROM MyTable
            WHERE Col2 = 'x'
            GROUP BY Col1
         ) dt
    

    No need to count rows in the sub-query, the result will be the same anyway.