I'm having a hard time describing my problem or finding it via Google.
I want to be able to group rows based on location
and employee
, but the group should be split if a row with the same location
occurs.
Basically a way to determine shifts. If another employee logs a row at the same location then the last created_at
should be the end date of the previous employee.
Starting from this (employee_logs
):
location | employee | created_at
---------+----------+--------------------
A | Bart | 2015-09-01 09:00:00
B | Homer | 2015-09-01 09:05:00
A | Bart | 2015-09-01 09:30:00
A | Bart | 2015-09-01 10:00:00
A | Homer | 2015-09-01 10:05:00
A | Homer | 2015-09-01 11:05:00
A | Bart | 2015-09-01 12:00:00
A | Bart | 2015-09-01 14:00:00
The desired result is (shifts):
location | employee | start | end
---------+----------+---------------------+---------------------
A | Bart | 2015-09-01 09:00:00 | 2015-09-01 10:00:00
B | Homer | 2015-09-01 09:05:00 | 2015-09-01 09:05:00
A | Homer | 2015-09-01 10:05:00 | 2015-09-01 11:05:00
A | Bart | 2015-09-01 12:00:00 | 2015-09-01 14:00:00
The hard part is that the sequence should be interrupted when another person creates a log at the same location. I can't seem to solve this with the usual techniques.