计算mysql中分组行的数量

时间:2023-01-28 00:16:42

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

在表xyz中,我有一行称为组件和一个labref行,它具有labref编号,如下所示

Table xyz

表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

我想对组件进行分组,然后计算返回的行数等于3,我编写了下面的sql查询,但它没有帮助实现我的目标,而是为每个组件返回4

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

The query returns

查询返回

Table xyz

表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 work around is appreciated

我现在想要实现的是,从上面的结果,行计数,并返回3作为行数,任何工作是值得赞赏的

3 个解决方案

#1


23  

You need to do -

你需要做 -

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

You can also avoid subquery as suggested by @hims056 here

您也可以按照@ hims056的建议避免使用子查询

#2


76  

Try this simple query without a sub-query:

在没有子查询的情况下尝试这个简单的查询:

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

See this SQLFiddle

#3


0  

It Simple you used GROUP BY Or DISTINCT

很简单你使用GROUP BY或DISTINCT

SELECT COUNT(DISTINCT component) AS Totalcount
FROM abc
WHERE labref = 'NDQA201303001'

#1


23  

You need to do -

你需要做 -

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

You can also avoid subquery as suggested by @hims056 here

您也可以按照@ hims056的建议避免使用子查询

#2


76  

Try this simple query without a sub-query:

在没有子查询的情况下尝试这个简单的查询:

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

See this SQLFiddle

#3


0  

It Simple you used GROUP BY Or DISTINCT

很简单你使用GROUP BY或DISTINCT

SELECT COUNT(DISTINCT component) AS Totalcount
FROM abc
WHERE labref = 'NDQA201303001'