我想创建一种出勤类型的表,我从打孔机获取值,如下所示:
UID | Time
023 | 2019-01-29 20:06:53
023 | 2019-01-29 20:07:10
023 | 2019-01-29 20:22:05
123 | 2019-01-30 08:57:01
027 | 2019-01-30 09:14:14
023 | 2019-01-30 11:22:21
123 | 2019-01-30 18:35:53
027 | 2019-01-30 19:00:25
现在所有数据都放在一个表中,因此我想要用户和按日期分组的第一个和最后一个输入,然后从2个值中获取时差
我需要这样的输出:
UID | In Time | Out Time | Time Diff.
023 | 2019-01-29 20:06:53 | 2019-01-29 20:22:05 | 00:18:00
027 | 2019-01-30 09:14:14 | 2019-01-30 19:00:25 | 10:00:00
123 | 2019-01-30 08:57:01 | 2019-01-30 18:35:53 | 10:00:00
首先,我尝试获取这样的数据,但这对我不起作用
$select = mysqli_query ($db, "SELECT *, Min(Date) AS MinDate, Max(Date) AS MaxDate FROM demotable GROUP BY UID");
答案 0 :(得分:2)
您可以使用TIMEDIFF()
:
SELECT
UID,
Min(timecolumn) AS `In Time`,
Max(timecolumn) AS `Out Time`,
TIMEDIFF(Max(timecolumn), Min(timecolumn)) AS `Time Diff`
FROM demotable
GROUP BY UID, DATE(timecolumn)
答案 1 :(得分:0)
对于同一天的时差,可以使用group by子句。 根据您的输出-当天没有超时,请不要显示该行-为此,您可以通过检查当天的max(time)不等于min(time)来使用HAVING子句。
SELECT
UID,
Min(Time) AS `In Time`,
Max(Time) AS `Out Time`,
TIMEDIFF(Max(Time), Min(Time)) AS `Time Diff`
FROM demo
GROUP BY UID, DATE(Time)
HAVING Max(Time) != Min(Time)
您也可以看到正在运行的演示 Demo on dbfiddle