Reputation: 697
I want to show the names of all employees from the EMPLOYEES
table who are working on more than three projects from the PROJECT
table.
PROJECTS.PersonID
is a a foreign key referencing EMPLOYEES.ID
:
SELECT NAME, ID
FROM EMPLOYEES
WHERE ID IN
(
SELECT PersonID, COUNT(*)
FROM PROJECTS
GROUP BY PersonID
HAVING COUNT(*) > 3
)
Can I have both PersonID
, COUNT(*)
in that subquery, or there must be only one column?
Upvotes: 3
Views: 7875
Reputation: 129
To answer your question, you can only have 1 column for the IN subquery. You could get your results using the query below:
SELECT e.ID
,e.Name
FROM dbo.Projects p
LEFT OUTER JOIN dbo.Employees e
ON p.PersonID = e.ID
GROUP BY e.ID
,e.Name
HAVING COUNT(*) > 3
Upvotes: 1
Reputation: 453028
Not in an IN
clause (or at least not the way you are trying to use it. Some RDBMSs allow tuples with more than one column in the IN
clause but it wouldn't help your case here)
You just need to remove the COUNT(*)
from the SELECT
list to achieve your desired result.
SELECT NAME, ID
FROM EMPLOYEES
WHERE ID IN
(
SELECT PersonID
FROM PROJECTS
GROUP BY PersonID
HAVING COUNT(*) > 3
)
If you wanted to also return the count you could join onto a derived table or common table expression with more than one column though.
SELECT E.NAME,
E.ID,
P.Cnt
FROM EMPLOYEES E
JOIN (SELECT PersonID,
Count(*) AS Cnt
FROM PROJECTS
GROUP BY PersonID
HAVING Count(*) > 3) P
ON E.ID = P.PersonID
Upvotes: 6