SET NOCOUNT ON
[green]-- Setup test data[/green]
Declare @Data Table(CompanyId VarChar(3), Time DateTime, Duration Int)
Insert Into @Data Values('AAA','13:09',3)
Insert Into @Data Values('AAA','13:10',2)
Insert Into @Data Values('AAA','13:11',1)
Insert Into @Data Values('BBB','15:04',1)
Insert Into @Data Values('BBB','15:32',1)
Insert Into @Data Values('CCC','18:25',2)
Insert Into @Data Values('CCC','18:26',1)
Insert Into @Data Values('DDD','20:05',4)
Insert Into @Data Values('DDD','20:06',3)
Insert Into @Data Values('DDD','20:07',2)
Insert Into @Data Values('DDD','20:08',1)
Insert Into @Data Values('EEE','22:35',1)
[green]-- create a table variable with RowId Column[/green]
Declare @Temp Table(RowId Int Identity(1,1), CompanyId VarChar(3), Time DateTime)
Insert Into @Temp(CompanyId, Time)
Select CompanyId, Time
From @Data
Order By CompanyId, Time
[green]-- Get the transitions[/green]
Declare @Range Table(RangeId Int Identity(1,1), RowId Int, CompanyId VarChar(20))
Insert Into @Range(RowId, CompanyId)
Select Min(RowId) As RowId, CompanyId
From @Temp
Group By CompanyId
Union All
Select Max(RowId), CompanyId
From @Temp
Group By CompanyId
Union All
Select A.RowId, A.CompanyId
From @Temp As A
Inner Join @Temp As B
On A.CompanyId = B.CompanyId
And A.RowId = B.RowId - 1
And A.Time <> DateAdd(Minute, -1, B.Time)
Union All
Select B.RowId, B.CompanyId
From @Temp As A
Inner Join @Temp As B
On A.CompanyId = B.CompanyId
And A.RowId = B.RowId - 1
And A.Time <> DateAdd(Minute, -1, B.Time)
Order By CompanyId, RowId
[green]-- Final query to merge the transitions
-- back to the original data.[/green]
Select T.CompanyId, T.Time, Ranges.MaxRow - RowId + 1 As Duration
From @Temp T
Inner Join (
Select A.RowId As MinRow, B.RowId As MaxRow
From @Range As A
Inner Join @Range As B
On A.RangeId = B.RangeId - 1
And A.RangeId % 2 = 1
) As Ranges
On T.RowId Between Ranges.MinRow And Ranges.MaxRow