-2

我有一个名为 ProjectRessources 的表,其中包含以下数据:

+-----------+------------+---------+-----------+
| projectId | employeeId | nbHours | wageHours |
+-----------+------------+---------+-----------+
| 1         | 1876       | 500     | 65        |
| 1         | 4354       | 2000    | 31        |
| 2         | 2231       | 250     | 55        |
| 3         | 1212       | 3000    | 35        |
| 3         | 1876       | 2000    | 35        |
| 3         | 2231       | 500     | 65   

我必须查询从事多个项目的员工才能获得以下信息:

+------------+----------------+
| employeeId | nbProjects |
+------------+----------------+
| 1876       | 2              |
| 2231       | 2              |
+------------+----------------+

我努力了

    SELECT DISTINCT employeeID,projectID
    FROM ProjectRessources
    WHERE COUNT(projectID) >1;

但我在使用 COUNT 时收到错误 1111

ERROR 1111 (HY000): Invalid use of group function

然后我尝试了这样的事情

SELECT DISTINCT
employeeId ,
COUNT(projectId) as nbProjects
From ProjectRessources
WHERE nbProjects >1;

但后来我得到以下错误

ERROR 1054 (42S22): Unknown column 'nbProjects' in 'where clause'

请帮助,任何反馈表示赞赏。请注意,我不允许使用 GROUP BY 进行查询。

4

3 回答 3

0

如果没有GROUP BY,您可以使用相关子查询来做到这一点:

SELECT *
FROM (
  SELECT DISTINCT pr.employeeId,
         (SELECT COUNT(*) FROM ProjectRessources pr2 WHERE pr2.employeeId = pr.employeeId) nbProjects 
  FROM ProjectRessources pr
) t
WHERE nbProjects > 1

如果projectId每次employeeId更改都存在重复 s 的情况COUNT(*)

SELECT COUNT(DISTINCT projectId) FROM ...

如果您的 MySql 版本是 8.0+ 并且每个没有重复projectId的 s employeeId,您可以使用COUNT(*)窗口函数来做到这一点:

SELECT *
FROM (
  SELECT DISTINCT employeeId,
         COUNT(*) OVER (PARTITION BY employeeId) nbProjects 
  FROM ProjectRessources pr
) t
WHERE nbProjects > 1

请参阅演示
结果:

> employeeId | nbProjects
> ---------: | ---------:
>       1876 |          2
>       2231 |          2
于 2021-01-02T17:31:51.937 回答
0

你想要having。. . 和权利group by

SELECT employeeID
FROM ProjectRessources
GROUP BY employeeId
HAVING COUNT(*) > 1;

如果您想要项目列表,我建议GROUP_CONCAT()

SELECT employeeID, GROUP_CONCAT(projectID) as projectIDs
FROM ProjectRessources
GROUP BY employeeId
HAVING COUNT(*) > 1;
于 2021-01-02T16:51:26.703 回答
0

您可以尝试将ProjectResources表与自身连接,如下所示:

select distinct p1.employeeID from
ProjectResources p1 join ProjectResources p2
    on p1.employeeID = p2.employeeID and
       p1.projectID <> p2.projectID

这只是尝试查看每一行是否有另一行具有相同的employeeID值但不同的projectID值。只要至少有一个,我们不在乎它们有多少,这就是为什么我们select distinct不会employeeID出现多次(如果没有distinct关键字,我们将为员工的每个项目获得一行从事)。

我使用您更新问题中的表格在 sqlfiddle.com 上创建了一个实际表格。下次您可以(并且应该)自己执行此操作并在您的问题中发布链接。

看演示

但这听起来有点像家庭作业。

如果您必须进行计数:

select distinct employeeID, count(*) OVER(PARTITION By employeeID) as nbProjects from (
   select p1.employeeID from
   ProjectResources p1 join ProjectResources p2
       on p1.employeeID = p2.employeeID and
          p1.projectID <> p2.projectID
  ) sq;
员工ID nb项目
1876年 2
2231 2

在 DB Fiddle 上查看

于 2021-01-02T17:03:49.457 回答