2

我不能让它工作。我需要首先找到假期和病假时间的最大总和,然后找到哪些员工的假期和病假时间总和具有此值。我可以得到 168 的最大值,但无论我如何安排事情,我似乎都无法获得符合此标准的员工 - 我只是获得所有员工的完整列表。下面的代码是最后一次尝试,基于类方向。谢谢!

SELECT e.employeeID, SUM(e.vacationhours + e.sickleavehours) AS maxHours
    FROM   humanresources.employee e 
    WHERE  EXISTS (
                   SELECT SUM(e.vacationhours + e.sickleavehours) AS totalhours 
                   FROM   humanresources.employee e) 
    GROUP  BY e.employeeID
4

4 回答 4

7

TOP WITH TIES简化了这个问题...

如果您只想要一个总小时数最多的员工列表......您可以简单地按总和排序,然后选择前 1 个,包括任何关系,以便它返回具有最大值的所有员工:

SELECT TOP 1 WITH TIES
    e.employeeID,
    SUM(e.vacationhours + e.sickleavehours) AS totalHours
FROM humanresources.employee e 
GROUP BY e.employeeID
ORDER BY totalHours DESC;
于 2012-04-13T17:31:05.990 回答
2

看一下Having条款

于 2012-04-13T17:31:58.250 回答
2

我会这样做,而不使用特定的 SQL 服务器语法。我想这应该适用于大多数 DBMS:

SELECT e.employeeID,
    SUM(e.vacationhours + e.sickleavehours) AS totalHours
FROM humanresources.employee e 
GROUP BY e.employeeID
HAVING SUM(e.vacationhours + e.sickleavehours) >= all
  (SELECT SUM(e.vacationhours + e.sickleavehours) FROM humanresources
   GROUP BY employeeID)
于 2012-04-13T17:43:51.360 回答
0

您有一个名为的表employee,并且在该表中您有一个名为 的字段employeeID。除非这是一个非常糟糕的命名情况,否则它是表employeeID的主键employee

没有必要做一个group by。您可以在 where 子句中过滤行。

select e.employeeID, e.vacationhours + e.sickleavehours as Hours
from employee as e
where e.vacationhours + e.sickleavehours = (select max(vacationhours + sickleavehours)
                                            from employee)
于 2012-04-13T18:02:55.017 回答