I have a Stored Procedure that retrieves employee daily summary intime - outtime:
SELECT ads.attendancesumid,
ads.employeeid,
ads.date,
ads.day, -- month day number
ads.intime,
ads.outtime
--employee shift intime and outtime
ss.intime,
ss.outtime
FROM employee_attendance_daily_summary ads
JOIN employee emp
ON emp.employeeid = ads.employeeid
JOIN setup_shift ss
ON ss.shiftcode = emp.shiftcode
AND DATEPART(dw, ads.date) = ss.day
WHERE ads.employeeid = 4 -- just to filter one employee
The result of the query is something like this:
Each day
is repeated 3 times because table setup_shift
(employee shifts) has:
Monday to Sunday for 3 different shift types: DAY, AFTERNOON and NIGHT.
Here is the same info but with the shift type column:
What I need is to ONLY get 1 row per day but with the closest employee shift depending on the
intime
andouttime
.
So the desire result should looks like this:
Any clue on how to do this? Appreciate it in advance.
I have also these case where intime
is 00:00:00
but outtime
has a value:
UPDATE:
HERE IS THE SQL FIDDLE
Try this man,I just take the minimum time difference of the each set
datediff(mi,intime,shift_intime)
This would be much easier if the times were in seconds after midnight, rather than in a
time
,datetime
, or string format. You can convert them using the formula:(Part of this is just my own discomfort with all the nested functions needed to handle other data types.)
So, let me assume that you have a series of similar columns measured in seconds. You can then approach this problem by taking the overlap with each shift and choosing the shift with the largest overlap.