是否可以在没有连接的情况下按计数(不同)进行分组?

时间:2011-11-21 17:15:06

标签: mysql join group-by distinct

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。

2 个答案:

答案 0 :(得分:3)

是:

select count(*) from
(select CompanyID from Employee group by CompanyID having count(*) > 1) v

或范围:

select count(*) from
(select CompanyID from Employee group by CompanyID 
 having count(*) >= 5 and count(*) < 10) v

答案 1 :(得分:0)

是的,可以使用子查询:

SELECT COUNT(*)
FROM
  ( SELECT 1
    FROM Employee 
    GROUP BY CompanyID 
    HAVING COUNT(*) > 1
  ) AS grp

或:

SELECT COUNT(DISTINCT CompanyID) 
FROM Employee AS e
WHERE EXISTS
      ( SELECT *
        FROM Employee AS e2
        WHERE e2.CompanyID = e.CompanyId
          AND e2.EmpID <> e.EmpID
      )

或者如果COUNT(*)速度很慢,您可以使用MIN()MAX()

SELECT COUNT(*)
FROM
  ( SELECT 1 
    FROM Employee 
    GROUP BY CompanyID 
    HAVING MAX(EmpID) > MIN(EmpId)
  ) AS grp