I have login and logout table of call center agents, these agents have a work shift from 22 to 06, so what I need to calculate is the min of loginTime and max of logOutTime, but this is where it becomes complex, because there are cases where an agent is disconnected during that time range, then another login event is created in the database on the same day where another shift begins and so on.
I've tried to manage results with ROW_NUMBER functions and using MIN and MAX with ROWS PRECEDING and FOLLOWING but it didn't work, my code:
SELECT agentId
,position
,loginDate
,loginTime
,logoutDate
,logoutTime
,MIN((CAST(loginDate AS DATETIME) + CAST(loginTime AS DATETIME)))
OVER(PARTITION BY agentId, position ORDER BY agentId, loginDate, loginTime) minLoginTime
,MAX((CAST(logoutDate AS DATETIME) + CAST(logoutTime AS DATETIME)))
OVER(PARTITION BY agentId, position ORDER BY agentId, loginDate, loginTime ROWS BETWEEN 0 PRECEDING AND 1 FOLLOWING) maxLogoutTime
FROM @tbl
ORDER BY loginDate
,loginTime
,logoutDate
,logoutTime
This is the table example:
DECLARE @tbl TABLE(agentId VARCHAR(10), position VARCHAR(10), loginDate DATE, loginTime TIME(0), logoutDate DATE, logoutTime TIME(0))
INSERT INTO @tbl SELECT '311338', '230025', '2019-06-03', '21:59:00', '2019-06-04', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230025', '2019-06-04', '21:59:00', '2019-06-04', '23:30:00'
INSERT INTO @tbl SELECT '311338', '230025', '2019-06-04', '23:31:00', '2019-06-05', '06:01:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-05', '21:59:00', '2019-06-06', '02:13:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-06', '02:14:00', '2019-06-06', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230037', '2019-06-06', '22:00:00', '2019-06-07', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-07', '21:59:00', '2019-06-08', '00:53:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-08', '00:53:00', '2019-06-08', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-09', '22:00:00', '2019-06-10', '06:09:00'
SELECT agentId
,position
,(CAST(loginDate AS DATETIME) + CAST(loginTime AS DATETIME)) loginTime
,(CAST(logoutDate AS DATETIME) + CAST(logoutTime AS DATETIME)) logoutTime
FROM @tbl
The expected result for agentId 311338 would be:
Day 2019-05-06: minLogin = 2019-06-05 21:59:00.000 maxLogout = 2019-06-06 06:00:00.000
Day 2019-06-06: minLogin = 2019-06-06 22:00:00.000 maxLogout = 2019-06-07 06:00:00.000
Day 2019-06-07: minLogin = 2019-06-07 21:59:00.000 maxLogout = 2019-06-08 06:00:00.000
Day....
As you can see no time must be discarded, if there's more than one login event on the same date, I have to check if it is part of the last day shift or part of the next day shift.
Hope you guys can help me.