我有这样的查询:
SELECT id, id_employee, hours FROM WorkHours WHERE hours > 8;
如何为此查询选择的每个人选择上一个员工工作记录?
所以,对于这样的表(id,id_employee,hours):
1 - 1 - 5
2 - 2 - 3
3 - 1 - 9
4 - 1 - 4
5 - 2 - 4
6 - 2 - 10
7 - 2 - 7
8 - 1 - 7
9 - 2 - 9
将选择记录3,6和9。我还得到了什么记录1,5,7。基本上,每当有人加班时,我想看看这个人在之前录制的那一天有多少小时。
答案 0 :(得分:1)
您可以使用相关子查询获取之前的id
:
SELECT wh.id, wh.id_employee, wh.hours,
(SELECT MAX(wh2.id)
FROM WorkHours wh2
WHERE wh2.id_employee = wh.id_employee AND wh2.id < wh.id
) as prev_id
FROM WorkHours wh
WHERE wh.hours > 8;
然后,要获得完整行,请使用JOIN
:
SELECT eh.*, wh.*
FROM (SELECT wh.id, wh.id_employee, wh.hours,
(SELECT MAX(wh2.id)
FROM WorkHours wh2
WHERE wh2.id_employee = wh.id_employee AND wh2.id < wh.id
) as prev_id
FROM WorkHours wh
WHERE wh.hours > 8
) eh LEFT JOIN
WorkHours wh
ON wh.id_employee = eh.id_employee;