1

我有一个表,它将在一天中添加几个时间戳条目,每个条目都有一个特定的员工 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但我不确定如何在列中获得最大值

4

1 回答 1

1

真的,您只需要聚合MAX()并按MIN(). employeeID使用该TIMEDIFF()函数计算两者之间的时间差。

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`
于 2013-01-14T02:51:45.057 回答