74

In a table xyz I have a row called components and a labref row which has labref number as shown here

Table xyz

labref             component
NDQA201303001          a
NDQA201303001          a
NDQA201303001          a
NDQA201303001          a
NDQA201303001          b
NDQA201303001          b
NDQA201303001          b
NDQA201303001          b
NDQA201303001          c
NDQA201303001          c
NDQA201303001          c
NDQA201303001          c

I want to group the components then count the rows returned which equals to 3, I have written the below SQL query but it does not help achieve my goal instead it returns 4 for each component

SELECT DISTINCT component, COUNT( component ) 
FROM `xyz`
WHERE labref = 'NDQA201303001'
GROUP BY component

The query returns

Table xyz

labref         component   COUNT(component)       
NDQA201303001   a           4
NDQA201303001   b           4
NDQA201303001   c           4

What I want to achieve now is that from the above result, the rows are counted and 3 is returned as the number of rows, Any workaround is appreciated

2
  • You mean you want 3 as an output in this case?
    – Himanshu
    Commented May 16, 2013 at 10:13
  • 1
    select count(DISTINCT component) from xyz Commented May 16, 2013 at 10:19

6 Answers 6

149

Try this simple query without a sub-query:

SELECT COUNT(DISTINCT component) AS TotalRows
FROM xyz
WHERE labref = 'NDQA201303001';

See this SQLFiddle

11
  • 3
    Of course this is the best solution, because it doesn't require a subquery.
    – Meloman
    Commented Dec 21, 2016 at 15:58
  • 1
    Best Solution. This solution should be accepted as this is simpler and better approach Commented Aug 25, 2017 at 19:51
  • 14
    This will work if you don't have "GROUP BY". If query has "Group By" then all rows will have 1.
    – Bala
    Commented Dec 20, 2017 at 3:07
  • 2
    @JohnySkovdal - You've made a fiddle to answer a different question, so saying this answer "does not work" is incorrect. As your fiddle shows, this answer correctly reports the number of distinct values. Commented Jan 20, 2019 at 2:38
  • 6
    @JoelEnanodJr, Bala - You wouldn't use "Group By" with this answer; this answer is an alternative approach, that doesn't need (nor tolerate) "Group By" in the query. OP only used "Group By" as an attempt to get the answer they need. Combining "Group By" with "Count(Distinct)" is not meaningful; Remove "Group By" from your query. Commented Jan 20, 2019 at 2:41
64

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

6
  • @Kshitij - Why to use subquery when we can do it directly?
    – Himanshu
    Commented May 16, 2013 at 10:28
  • 2
    hims056' solution is the better one - avoid subquerys if you're able to
    – fubo
    Commented Nov 11, 2014 at 16:01
  • 11
    Add alias after closing parenthesis.
    – Gene Kelly
    Commented Oct 22, 2015 at 18:42
  • 2
    The reason for this answer is that it will work when you need a having clause. The answer below relies on being able to rewrite the query without a having clause. Commented Jul 3, 2019 at 15:23
  • @MarlinPierce: Just to be curious, may I know an example of the scenario you have mentioned?
    – Himanshu
    Commented Jul 17, 2023 at 6:47
12

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.

4
  • 2
    This is the correct way of doing this. Works even when using limit x.
    – John C
    Commented Apr 30, 2021 at 16:22
  • 1
    Note that you need to be on MySQL 8+ to use OVER() (and other window functions). Commented Feb 11, 2022 at 4:46
  • It didn't worked. Commented Jul 5, 2023 at 11:29
  • @menoktaokan check your sql version and your query
    – nojitsi
    Commented Jul 6, 2023 at 12:06
0

Why not use num_rows.

If you do it using this method, You don't have to modify the query in any way.

if ($result = $mysqli->query("SELECT DISTINCT component, COUNT( component ) 
    FROM `xyz`
    WHERE labref = 'NDQA201303001'
    GROUP BY component")){

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}
3
  • 1
    Shorter code if nest selects: select count(1) from ( ... ) t; will yield row count of any query [with some limitations, specifically inner query must not have duplicate column names], where "..." is the query you are counting. For performance, can also change inner SELECT DISTINCT component, COUNT( component ) FROM to SELECT DISTINCT component FROM. Commented Jan 20, 2019 at 2:51
  • It should also be noted that bringing in a large table into PHP may hit an overload memory limit for PHP and "Fatal Error" the code. Easier on memory to allow MySQL to count the rows. Commented Dec 5, 2020 at 19:41
  • Because that gives you total rows returned from table, not total rows in table matching the query. Try adding a limit 10 of a query that has 1000.
    – John C
    Commented Apr 30, 2021 at 16:21
-1

There is also:

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

Which should return:

labref component count
NDQA201303001 a 4
NDQA201303001 b 4
NDQA201303001 c 4

And, bonus points (I hope), no subqueries!

Based on this source.

-2

Select labref , component ,Count(*) as Counts From xyz Group by labref , component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.