Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

sql query - Ottieni la differenza di tempo tra lo swipe in - Swipe out per il dipendente

select    empid,
          sum
          (
              datediff
              (
              MINUTE, 
              case when timesheet.timein < @timeframe_start 
                  then @timeframe_start  
                  else timesheet.timein end, 
              case when timesheet.timeout > @timeframe_end 
                  then @timeframe_end 
                  else timesheet.timeout end
              )
          ) as total_duration
from     (
         select    timein.empid, 
                   timein.swipe_time as timein, 
                   timeout.swipe_time as timeout
         from      tbltest timein
         left join tblTest timeout 
         on        timein.empid = timeout.empid
         and       timeout.eventtype = 'ex'
         and       timeout.swipe_time = 
             (
             select     MIN(swipe_time) 
             from       tblTest tcheck 
             where      tcheck.empid = timeout.empid 
             and        tcheck.eventtype = 'EX' 
             and        tcheck.swipe_time > timein.swipe_time
             )
         where      timein.eventtype = 'en'
         ) timesheet
where    timesheet.timein between @timeframe_start and @timeframe_end
or       timesheet.timeout between @timeframe_start and @timeframe_end
or       (
         timesheet.timein < @timeframe_start 
         and timesheet.timeout > @timeframe_end
         )
group by empid
order by 2 desc