2

我正在尝试选择在每个项目上工作时间最长的员工,但它只是为每个 projectID 选择第一个属性。

分配表:

+-----------+----------------+-------------+
| ProjectID | EmployeeNumber | HoursWorked |
+-----------+----------------+-------------+
|      1000 |              1 |       30.00 |
|      1000 |              8 |       75.00 |
|      1000 |             10 |       55.00 |
|      1100 |              4 |       40.00 |
|      1100 |              6 |       45.00 |
|      1200 |              1 |       25.00 |
|      1200 |              2 |       20.00 |
|      1200 |              4 |       45.00 |
|      1200 |              5 |       40.00 |
|      1300 |              1 |       35.00 |
|      1300 |              8 |       80.00 |
|      1300 |             10 |       50.00 |
|      1400 |              4 |       15.00 |
|      1400 |              5 |       10.00 |
|      1400 |              6 |       27.50 |
+-----------+----------------+-------------+

我的视图表显示在每个项目上工作时间最长的员工:

+----------------+-------+-----------+
| EmployeeNumber | MAX   | ProjectID |
+----------------+-------+-----------+
|              1 | 75.00 |      1000 |
|              4 | 45.00 |      1100 |
|              4 | 45.00 |      1200 |
|              1 | 80.00 |      1300 |
|              4 | 27.50 |      1400 |
+----------------+-------+-----------+

关于为什么显示员工编号 1、4、4、1、4 而不是 8、6、4、8、6 的任何想法?

4

1 回答 1

1

不确定是否有任何一个答案有这个。

Select project_id , max(hoursworked) 
FROM Assignment AS A JOIN Employee AS E
ON A.EmployeeNumber = E.EmployeeNumber
GROUP BY A.PROJECTID

此查询告诉您项目的最大工作时间。将其加入查询以获取执行此操作的员工 ID。

CREATE VIEW MostHours AS
SELECT E.EmployeeNumber, qry.hoursworked, ProjectID
FROM Assignment AS A JOIN Employee AS E
ON A.EmployeeNumber = E.EmployeeNumber
inner join 
   ( Select project_id , max(hoursworked) hoursworked
    FROM Assignment AS A JOIN Employee AS E
    ON A.EmployeeNumber = E.EmployeeNumber
    GROUP BY A.PROJECTID) qry
on a.projectID = qry.projectid and a.hoursworked = qry.hoursworked

我认为这在语法上是正确的......对不起,我没有一个 mysql 区域来测试它。逻辑很简单...使用子查询来定位 projectID 和最大工作时间,将其内部连接回员工/分配查询。这起到过滤器的作用,只留下 projectID 的最大工作时间。当 2 个人的工作时间相同时,此方法还有一个额外的好处,即为一个项目返回两行。

顺便说一句...您看到的当前行为的原因完全是 MYSQL。大多数其他引擎会直接返回一个错误,指出employeeID 不是group by 语句的一部分并且在那里失败。MYSQL 出于某种原因决定它没问题并随机带回一个employeeID(或任何未在组中正确指定的字段)

编辑:

如果我们不在 MYSQL 中,那将是可行的。解决方法是两种观点,而不是一种观点……请参阅我最近评论中的链接:

 Create view maxmosthours AS
    Select project_id , max(hoursworked) hoursworked
    FROM Assignment AS A JOIN Employee AS E
    ON A.EmployeeNumber = E.EmployeeNumber
    GROUP BY A.PROJECTID

CREATE VIEW MostHours AS
SELECT E.EmployeeNumber, qry.hoursworked, ProjectID
FROM Assignment AS A JOIN Employee AS E
ON A.EmployeeNumber = E.EmployeeNumber
inner join maxmosthours qry
on a.projectID = qry.projectid and a.hoursworked = qry.hoursworked

那是 MYSQL 中限制的 %^%@$%

于 2013-09-30T18:04:47.027 回答