SQL 服务器 - 计算每个不同公司的员工人数

SQL Server - For each distinct company count the number of employees

我正在尝试创建一些 SQL 来计算每家公司的员工人数,并且 return 只计算员工人数大于或等于 n 的公司。

我有下表(简化):

CompanyEmployee Table

ID    Name         IsCompany
1     John Joe     0
2     Company Y    1
3     Company X    1
4     Sally Jeff   0
5     James Peach  0

Employment Table
ID    EmployeeID    CompanyID
1     1             2
2     4             3
3     5             3

我想要的 n=2 结果:

ID    Name         IsCompany
3     Company X    1

我有以下 SQL:

SELECT t.* FROM CompanyEmployee AS t 
WHERE t.ID IN ( 
  SELECT DISTINCT (t.ID) 
  FROM CompanyEmployee AS t  
  INNER JOIN Employment AS t0 ON t.ID = t0.CompanyID 
  WHERE t.IsCompany = 1
  GROUP BY t0.CompanyID
  HAVING COUNT(t0.EmployeeID) >= n)

但它会产生以下错误:

Column 'CompanyEmployee.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

如有任何帮助或建议,我们将不胜感激!

试试这个:

SELECT t1.CompanyId, t2.CompanyName, COUNT(t1.CompanyId)
FROM Employment AS t1 INNER JOIN CompanyEmployee AS t2 ON t1.CompanyId = t2.Id
GROUP BY t1.CompanyId, t2.CompanyName
HAVING COUNT(t1.CompanyId)>=n

其中 n 是员工人数...

以这种方式混合公司和员工不是一个好主意。只要两种不同类型的行之间的 id 值从不相交,使用直接内部连接就可以工作。我想如果它是一个标识列,那是不应该发生的。

with Companies as (
    select ID as CompanyID, Name
    from CompanyEmployee
    where IsCompany = 1
), Employees as (
    select CompanyID, Name
    from CompanyEmployee where
    IsCompany = 0
)
select c.CompanyID, Name, 1 as IsCompany
from
    Companies as c
    inner join Employment as ec on ec.CompanyID = c.CompanyID
    inner join Employees as e on e.EmployeeID = ce.EmployeeID
group by
    c.CompanyID
having count(*) >= n

还有一个简单的方法可以做到:

select *
from CompanyEmployee
where ID in (
    select CompanyID
    from Employment
    group by CompanyID
    having count(*) >= n)
)