Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 302
D.R. Avatar asked Nov 29 '22 10:11

D.R.


2 Answers

SELECT COUNT(*)
FROM (
    SELECT value = COUNT(*)
    FROM MyTable
    WHERE Col2 = 'x'
    GROUP BY Col1
) е

but i think - you need to try this query -

SELECT COUNT(DISTINCT Col1)
FROM MyTable
WHERE Col2 = 'x'
like image 153
Devart Avatar answered Dec 21 '22 23:12

Devart


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.

like image 21
jarlh Avatar answered Dec 22 '22 00:12

jarlh