Counting number of grouped rows in mysql

后端 未结 5 681
有刺的猬
有刺的猬 2021-01-31 14:22

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         


        
相关标签:
5条回答
  • 2021-01-31 14:22

    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

    0 讨论(0)
  • 2021-01-31 14:30

    Try this simple query without a sub-query:

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

    See this SQLFiddle

    0 讨论(0)
  • 2021-01-31 14:32

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

    0 讨论(0)
  • 2021-01-31 14:33

    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();
    }
    
    0 讨论(0)
  • 2021-01-31 14:48

    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.

    0 讨论(0)
提交回复
热议问题