简体   繁体   中英

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

I am trying to create some SQL that will count the number of employees within each company and return only those companies with greater than or equal to n employees.

I have the following tables (simplified):

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

My desired result for n=2 :

ID    Name         IsCompany
3     Company X    1

I have the following 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)

But it generates the following error:

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

Any help or advice would be greatly appreciated!

Mixing companies and employees this way is a bad idea. Using a straight inner join may work as long as the id values between the two different types of rows never intersect. I guess if it's an identity column then that's not supposed to happen.

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

There is still a straightforward way to do it:

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

Try this:

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

where n is a number of employees...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM