3

我想显示EMPLOYEES表中从事三个以上项目的所有员工的姓名PROJECT

PROJECTS.PersonID是一个外键引用EMPLOYEES.ID

SELECT NAME, ID 
FROM EMPLOYEES
WHERE ID IN
    ( 
    SELECT PersonID, COUNT(*)
    FROM PROJECTS
    GROUP BY PersonID
    HAVING COUNT(*) > 3
    )

我可以在那个子查询中同时拥有PersonID,COUNT(*)还是必须只有一列?

4

2 回答 2

5

不在IN子句中(或者至少不是您尝试使用它的方式。一些 RDBMS 允许在子句中包含多个列的元组,IN但在这里对您的情况没有帮助)

您只需COUNT(*)要从SELECT列表中删除 即可达到您想要的结果。

SELECT NAME, ID 
FROM EMPLOYEES
WHERE ID IN
    ( 
    SELECT PersonID
    FROM PROJECTS
    GROUP BY PersonID
    HAVING COUNT(*) > 3
    )

如果您还想返回计数,您可以连接到具有多个列的派生表或公用表表达式。

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
于 2012-09-20T23:10:43.260 回答
1

要回答您的问题,IN 子查询只能有 1 列。您可以使用以下查询获得结果:

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
于 2012-09-20T23:20:29.630 回答