How to find out Firstin LastOut of Night Shift Employee in SQL Server -


i can firstin - lastout out of day shift employee using min(),max(). have problem night shift employee 5:30 pm next day morning 2:30 am. @ same day(next day) come again on 5:30 pm. not able calculate..

ex: shift table

  userid     shiftname    start   end         2267     night shift-1  17:30  02:30  

ex: employee table :

   userid     login                   logout                         logdate     2267   2016-01-04 20:52:08.000  2016-01-04 22:09:22.000   2016-01-04 00:00:00.000     2267   2016-01-04 23:00:07.000  2016-01-04 23:00:07.000   2016-01-04 00:00:00.000     2267   2016-01-05 00:35:46.000  2016-01-05 00:35:46.000   2016-01-05 00:00:00.000     2267   2016-01-05 01:02:31.000  2016-01-05 03:57:16.000   2016-01-05 00:00:00.000     2267   2016-01-05 18:43:50.000  2016-01-05 19:05:04.000   2016-01-05 00:00:00.000     2267   2016-01-05 19:10:20.000  2016-01-05 22:26:00.000   2016-01-05 00:00:00.000     2267   2016-01-05 23:27:24.000  2016-01-05 23:27:24.000   2016-01-05 00:00:00.000     2267   2016-01-06 03:45:16.000  2016-01-06 03:45:16.000   2016-01-06 00:00:00.000 

i want output :

        empid     date           firstin    lastout         2267    2016-01-04        20:52      03:57         2267    2016-01-05        18:43      03:45  

i think work better lead(). "out" date on same row , aggregation:

select userid, cast(logdate date) thedate,        min(logdate), max(next_logdate) (select l.*,              lead(logdate) on (partition userid order logdate) next_logdate       logintable l      ) l l.details = 'in' group userid, cast(logdate date) order userid, cast(logdate date); 

(this isn't doing conversion time focus on important part of logic.)

note: assumes the next log record 'in' record 'out' record. true of data in question.


Comments