我有这个查询
SELECT Date_Format(te.entry_datetime, '%Y-%m-%d') as Date,
te2.entry_datetime as Time_in,
te3.entry_datetime as Time_out,
TIMEDIFF(te7.entry_datetime, te6.entry_datetime) as Total_break
FROM time_entries te
JOIN time_entries te2 ON te.employee_index = te2.employee_index
AND te2.entry_type_index='1' AND te2.entry_datetime =
(SELECT entry_datetime
FROM time_entries
WHERE entry_type_index='1' AND employee_index = 22 AND entry_datetime = te.entry_datetime
GROUP BY entry_datetime)
LEFT JOIN time_entries te3 ON te.employee_index = te3.employee_index
AND te3.entry_type_index='2' AND te3.entry_datetime =
(SELECT entry_datetime
FROM time_entries
WHERE entry_type_index='2' AND employee_index = 22 AND entry_datetime > te.entry_datetime
ORDER BY
ABS(TIMESTAMPDIFF(SECOND, te.entry_datetime, 'entry_datetime'))
LIMIT 1)
LEFT JOIN time_entries te6 ON te.employee_index = te6.employee_index
AND te6.entry_type_index='6' AND te6.entry_datetime =
(SELECT entry_datetime
FROM time_entries
WHERE entry_type_index='6' AND employee_index = 22 AND entry_datetime > te.entry_datetime
ORDER BY
ABS(TIMESTAMPDIFF(SECOND, te.entry_datetime, 'entry_datetime'))
LIMIT 1)
LEFT JOIN time_entries te7 ON te.employee_index = te7.employee_index
AND te7.entry_type_index='7' AND te7.entry_datetime =
(SELECT entry_datetime
FROM time_entries
WHERE entry_type_index='7' AND employee_index = 22 AND entry_datetime > te.entry_datetime
ORDER BY
ABS(TIMESTAMPDIFF(SECOND, te.entry_datetime, 'entry_datetime'))
LIMIT 1)
这就是结果
| Date | Time_in | Time_out | Total_break |
| 2013-08-23 | 2013-08-30 09:00:00 | 2013-08-30 19:01:00 | 00:36:03 |
该查询工作正常,除了一个问题。Total_break 仅对一个中断时间的差值求和(entry_type_index 7 是 break_end,6 是 break_start)。我想总结某一天休息时间的所有差异(每个 entry_type_index 7 和 6)。
这是我的预期答案
| Date | Time_in | Time_out | Total_break |
| 2013-08-23 | 2013-08-30 09:00:00 | 2013-08-30 19:01:00 | 00:59:04 |
获取 entry_type_index 2 和 1 之间每个 entry_type_index 7 和 6 的差异,然后将它们全部相加。
这是我的表的示例输出(time_entries)
| employee_index | entry_type_index | entry_datetime |
| 22 | 2 | 2013-08-30 19:01:00 |
| 22 | 7 | 2013-08-30 16:29:07 |
| 22 | 6 | 2013-08-30 16:06:06 |
| 22 | 7 | 2013-08-30 15:40:06 |
| 22 | 6 | 2013-08-30 15:04:03 |
| 22 | 1 | 2013-08-30 09:00:00 |
感谢那些可以指导我这样做的人。