Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;with [Scans] as (
- select [Id], [EmployeeId], [ScanDateTime], [Status] from (values
- (7 , 87008, '2018-08-02 16:03:00.227', 1)
- ,(8 , 87008, '2018-08-02 16:06:17.277', 2)
- ,(9 , 87008, '2018-08-02 16:10:37.107', 3)
- ,(10, 87008, '2018-08-02 16:20:17.277', 2)
- ,(11, 87008, '2018-08-02 16:30:37.107', 3)
- ,(12, 87008, '2018-08-02 16:40:37.107', 2)
- ,(13, 87008, '2018-08-02 20:06:00.000', 4)
- ,(14, 87008, '2018-08-03 16:03:00.227', 1)
- ,(15, 87008, '2018-08-03 16:06:17.277', 2)
- ,(16, 87008, '2018-08-03 16:10:37.107', 3)
- ,(17, 87008, '2018-08-03 16:20:17.277', 2)
- ,(18, 87008, '2018-08-03 16:30:37.107', 3)
- ,(19, 87008, '2018-08-03 16:40:37.107', 2)
- ,(20, 87008, '2018-08-03 20:06:00.000', 4)
- ) as [v] (
- [Id], [EmployeeId], [ScanDateTime], [Status]
- )
- )
- select
- [EmployeeId] = [s].[EmployeeId]
- ,[StartTime] = [s].[ScanDateTime]
- ,[EndTime] = [et].[ScanDateTime]
- ,[BreakInMins] = [b].[BreakInMins]
- from
- [Scans] as [s] -- here is your table
- outer apply
- (
- select top 1 [ScanDateTime], [Id] from [Scans] where [Id] > [s].[Id] and [EmployeeId] = [s].[EmployeeId] and [Status] = 4 order by [ScanDateTime] asc
- ) as [et]
- outer apply
- (
- select
- [BreakInMins] = sum(isnull([r].[mins], datediff(mi, [sp].[ScanDateTime], getdate())))
- from
- [Scans] as [sp]
- outer apply
- (
- 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
- ) as [r]
- where
- [sp].[id] > [s].[id] and [sp].[id] < isnull([et].[id], [id] + 1)
- and [sp].[EmployeeId] = [s].[EmployeeId]
- and [sp].[Status] = 2
- ) as [b]
- where
- [Status] = 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement