是否可以在没有连接的情况下按计数(不同)进行分组?
Table 1 : (Company)
ID Name
1 A
2 B
3 C
每个公司 (pk = ID) 可以拥有一名或多名员工。
Table 2 : (Employee) (CompanyID referencing ID)
CompanyID EmpID Name
1 1 Joe
1 2 Doe
1 3 Boe
2 4 Lou
3 5 Su
3 6 Ram
查询:
select CompanyID, count(*) from Employee group by CompanyID having count(*) > 1; # Lists companies and their counts.
CompanyID count(*)
1 3
3 2
对于此查询,我只想要一个包含不同 CompanyID 计数的结果。因此,本例中为“2”[公司 A 和 C]。
简而言之,我正在寻找拥有 2 名或更多员工的公司数量。
是否有办法在没有临时表或连接的情况下获得结果?我正在使用MySQL。
Table 1 : (Company)
ID Name
1 A
2 B
3 C
Each company (pk = ID) can have one or more employees.
Table 2 : (Employee) (CompanyID referencing ID)
CompanyID EmpID Name
1 1 Joe
1 2 Doe
1 3 Boe
2 4 Lou
3 5 Su
3 6 Ram
Query :
select CompanyID, count(*) from Employee group by CompanyID having count(*) > 1; # Lists companies and their counts.
CompanyID count(*)
1 3
3 2
For this query, I want just one result with the count of distinct CompanyIDs. So, '2' in this case [Companies A and C].
In short, I am looking for number of companies with 2 or more employees.
Is there anyway to get the result without a temp table or a join? I am using MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是:
或对于范围:
Yes:
or for ranges:
是的,可以使用子查询:
或者:
或者如果
COUNT(*)
很慢,您可以使用MIN()
和MAX()
:Yes, it's possible with subqueries:
or:
or perhaps if
COUNT(*)
is slow, you can useMIN()
andMAX()
: