Counting number of grouped rows in mysql Counting number of grouped rows in mysql sql sql

Counting number of grouped rows in mysql


Try this simple query without a sub-query:

SELECT COUNT(DISTINCT component) AS TotalRowsFROM xyzWHERE labref = 'NDQA201303001';

See this SQLFiddle


You need to do -

SELECT    COUNT(*)FROM    (        SELECT            DISTINCT component        FROM            `multiple_sample_assay_abc`        WHERE            labref = 'NDQA201303001'    ) AS DerivedTableAlias

You can also avoid subquery as suggested by @hims056 here


I found the solution.So, if you want to count quantity of groups, not quantity of elements in each group, and return duplicate value to every group record in result table, you should use OVER() clause on you'r count function.

So, for example above the solution would be

SELECT component, COUNT(*) OVER() as number_of_components FROM `xyz` WHERE labref = 'NDQA201303001' GROUP BY component

I suppose that works with any query that use GROUP BY, additional info, check in the link above.