在特定列和行中获得最大价值

时间:2013-01-14 02:41:19

标签: mysql

我有一张桌子,它会在一天内添加几个时间戳条目,并且每个条目都附有一个特定的员工ID。我很好奇如何获得当天的第一个时间戳和当天的最后一个时间戳来计算特定员工在特定日期工作的时间。我的表格如下:

+----+------------+----------+---------+---------------------+-----------+------------+-----------+---------+
| id | employeeID | date     | timeIn  | jobDescription      | equipType | unitNumber | unitHours | timeOut |
+----+------------+----------+---------+---------------------+-----------+------------+-----------+---------+
|  1 |          1 | 01/13/13 | 8:17 pm | Worked in Hubbard   | Dozer     | 2D         |     11931 | 8:17 pm |
|  2 |          1 | 01/13/13 | 8:17 pm | Worked in Jefferson | Excavator | 01E        |      8341 | 8:18 pm |
+----+------------+----------+---------+---------------------+-----------+------------+-----------+---------+

到目前为止,我有一个这样的查询来检索时间值:

$stmt = $conn->prepare('SELECT * FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID ORDER BY employeeID ASC');
    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday));

但我不确定如何在timeOut

中获得最大价值

1 个答案:

答案 0 :(得分:1)

实际上,您只需要按MAX()分组的汇总MIN()employeeID。使用TIMEDIFF() function计算两者之间的时差。

SELECT 
  `employeeID`,
  MIN(`timeIn`) AS `timeIn`,
  MAX(`timeOut`) AS `timeOut`,
  TIMEDIFF(MAX(`timeOut`), MIN(`timeIn`)) AS `totalTime`
FROM `timeRecords`
WHERE
  `date` = :dateToday
  AND `employeeID` = :employeeID
/* Selecting only one employeeID you don't actually need the GROUP BY */
GROUP BY `employeeID`

但是,如果员工在一天内多次进出,则不会报告总工作时间。在这种情况下,您需要SUM()每个进/出对TIMEDIFF()的结果。

类似的东西:

SELECT
  `employeeID`,
  /* Assumes no times overlap across rows */
  SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) AS `totalTime`
FROM `timeRecords`
WHERE
  `date` = :dateToday
  AND `employeeID` = :employeeID
GROUP BY `employeeID`