Since you have SQL Server 2012, you can use TimeFromParts and "mod 8" to minimize work ...
select employeeId, accessCode, minDiff = MIN(ABS(DATEDIFF(TIMEFROMPARTS(DATEPART(HH,t.timestamp) % 8, (DATEPART(MI,t.timestamp), (DATEPART(S,t.timestamp),0,0), TIMEFROMPARTS(7, (DATEPART(MI,t.timestamp), (DATEPART(S,t.timestamp)) from table t were t.timestamp is in a given daily range
So, since your shift changes (7,15,23) are all โmod 8 = 7โ, I just compare the hourly part of the โ8โ timestamp with โ7โ - this way I don't need to run the request three times.
source share