SQL查找最大值然后查找其出现

时间:2012-04-13 17:24:59

标签: sql sql-server-2008 max

我无法让这个工作。 我需要先找到假期和病假的最大总和,然后找出哪些员工有这个假期和病假时间的总和。我可以得到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 个答案:

答案 0 :(得分:7)

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

如果您只想要一个拥有最大总数的员工列表......您只需按总和排序,然后选择前1,包括任何关系,以便它返回具有最大值的所有员工:< / p>

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;

答案 1 :(得分:2)

查看Having子句

答案 2 :(得分: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)

答案 3 :(得分:0)

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

无需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)