Advertisement
JuozasLT

Untitled

Aug 9th, 2018
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 2.10 KB | None | 0 0
  1. ;with [Scans] as (
  2.     select [Id], [EmployeeId], [ScanDateTime], [Status] from (values
  3.          (7 , 87008, '2018-08-02 16:03:00.227', 1)
  4.         ,(8 , 87008, '2018-08-02 16:06:17.277', 2)
  5.         ,(9 , 87008, '2018-08-02 16:10:37.107', 3)
  6.         ,(10, 87008, '2018-08-02 16:20:17.277', 2)
  7.         ,(11, 87008, '2018-08-02 16:30:37.107', 3)
  8.         ,(12, 87008, '2018-08-02 16:40:37.107', 2)                                                      
  9.         ,(13, 87008, '2018-08-02 20:06:00.000', 4)
  10.        
  11.         ,(14, 87008, '2018-08-03 16:03:00.227', 1)
  12.         ,(15, 87008, '2018-08-03 16:06:17.277', 2)
  13.         ,(16, 87008, '2018-08-03 16:10:37.107', 3)
  14.         ,(17, 87008, '2018-08-03 16:20:17.277', 2)
  15.         ,(18, 87008, '2018-08-03 16:30:37.107', 3)
  16.         ,(19, 87008, '2018-08-03 16:40:37.107', 2)                                                      
  17.         ,(20, 87008, '2018-08-03 20:06:00.000', 4)  
  18.     ) as [v] (
  19.         [Id], [EmployeeId], [ScanDateTime], [Status]
  20.     )
  21. )
  22. select
  23.      [EmployeeId]   =   [s].[EmployeeId]
  24.     ,[StartTime]    =   [s].[ScanDateTime]
  25.     ,[EndTime]      =   [et].[ScanDateTime]
  26.     ,[BreakInMins]  =   [b].[BreakInMins]
  27. from
  28.     [Scans] as  [s] --  here is your table
  29. outer apply
  30.     (      
  31.         select top 1 [ScanDateTime], [Id] from [Scans] where [Id] > [s].[Id] and [EmployeeId] = [s].[EmployeeId] and [Status] = 4 order by [ScanDateTime] asc
  32.     )       as  [et]
  33. outer apply
  34.     (
  35.         select
  36.               [BreakInMins] = sum(isnull([r].[mins], datediff(mi, [sp].[ScanDateTime], getdate())))
  37.         from
  38.             [Scans] as [sp]
  39.         outer apply
  40.             (
  41.                 select top 1 [mins] = datediff(mi, [sp].[ScanDateTime], [ScanDateTime]) from [Scans] where [Id] > [sp].[Id] and [EmployeeId] = [sp].[EmployeeId] and [Status] IN (3, 4) order by [ScanDateTime] asc
  42.             ) as [r]
  43.         where
  44.                 [sp].[id] > [s].[id] and [sp].[id] < isnull([et].[id], [id] + 1)
  45.             and [sp].[EmployeeId] = [s].[EmployeeId]
  46.             and [sp].[Status] = 2
  47.  
  48.     )       as  [b]    
  49. where
  50.         [Status] = 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement