通过查询简单的mysql组需要帮助

时间:2010-04-27 13:19:30

标签: sql mysql

当我添加显示的行...

时,此查询失败
Select Companyid, count(*) as cnt
from mytable
where State is not null
and cnt = 1  <------------------------- FAIL
group by CompanyID

有什么办法吗?

这是一个冗长的背景,如果它会帮助....

我有一个表查询。

以下是该表的示例:

CompanyID, State
1,OH
1,IL
1,NY
2,IL
3,NY
3,OH
4,NY
5,CA
5,WA

我想要一个会返回类似内容的查询:

2,IL
4,NY

到目前为止我有这个

Select Companyid, count(*) as cnt
from mytable
where State is not null
group by CompanyID

这给了我一个每家公司的记录数量。

IE:

1,3
2,1
3,2
4,1
5,2

现在我想将上面的列表过滤为只有两个记录的结果。

我尝试添加另一个where子句,但失败了:

Select Companyid, count(*) as cnt
from mytable
where State is not null
and cnt = 1  <-------------------- FAIL
group by CompanyID

2 个答案:

答案 0 :(得分:3)

您可以使用Having - 子句限制只在Group By中出现一次的记录:

Select companyId, state
From mytable
Where state Is Not Null
Group By companyId
Having Count(*) = 1

答案 1 :(得分:1)

cnt是一个总值。因此,它包含HAVING子句,而不是WHERE子句。

Select Companyid, count(*) as cnt 
from mytable 
where State is not null 
group by CompanyID 
HAVING count(*)=1;
相关问题