我正在进行SQL查询以执行以下操作:
对于两个以上员工工作的每个项目,检索项目编号,项目名称和从事该项目的员工人数。
这就是我目前对项目1的目的:
SELECT project.PNO, project.PNAME, COUNT(DISTINCT works_on.ESSN)
AS '# of employess worked on'
FROM project INNER JOIN works_on
ON project.PNO = works_on.PNO
INNER JOIN employee
ON works_on.ESSN = employee.SSN
HAVING COUNT(DISTINCT works_on.ESSN) > 2
AND project.PNO LIKE 1
然后它返回:
PNO:1
PNAME:ProductX
就业人数:7
当它应该返回NULL时,因为项目编号1在works_on表中只有两个不同的ESSN,而是返回works_on表中不同ESSN的总数
附件是我的架构:
答案 0 :(得分:2)
您需要按项目获得结果,这意味着您错过了group by
条款:
SELECT project.PNO,
project.PNAME,
COUNT(DISTINCT works_on.ESSN) AS '# of employess worked on'
FROM project
INNER JOIN works_on ON project.PNO = works_on.PNO
INNER JOIN employee ON works_on.ESSN = employee.SSN
GROUP BY project.PNO, project.PNAME -- Here!
HAVING COUNT(DISTINCT works_on.ESSN) > 2 AND project.PNO LIKE 1
答案 1 :(得分:0)
使用Group by和where子句,如下所示:
SELECT project.PNO, project.PNAME, COUNT(DISTINCT works_on.ESSN)
AS '# of employess worked on'
FROM project INNER JOIN works_on
ON project.PNO = works_on.PNO
INNER JOIN employee
ON works_on.ESSN = employee.SSN
where project.PNO LIKE 1
group by project.PNO, project.PNAME
HAVING COUNT(DISTINCT works_on.ESSN) > 2