Here's a solution that doesn't depend on SQL Server 2012:
declare @test-2 table
(Tsq INT IDENTITY (1,1),
Data Varchar (150),
ts datetime,
Tpkt_type int)
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:47:35.963','2') --1
insert into @test-2 values ('NS,000020,000021,000022,000023','2013-11-13 09:47:36.180','2')
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:47:37.007','2')
insert into @test-2 values ('GX,1,0000000000000000000000000','2013-11-13 09:47:37.007','4') --1
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:50:25.987','2') --2
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:50:26.190','2')
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:50:26.393','2')
insert into @test-2 values ('GX,1,0000000000000000000000000','2013-11-13 09:50:40.920','4') --2
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:51:28.330','2') --3
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:51:28.547','2')
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-11-13 09:51:28.767','2')
insert into @test-2 values ('GX,1,0000000000000000000000000','2013-11-13 09:51:43.257','4') --3
insert into @test-2 values ('NS,000020,000021,000022,000023','2013-12-17 16:51:09.063','18') --4
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-12-17 16:51:09.063','2')
insert into @test-2 values ('GS,000020,000021,000022,000023','2013-12-17 16:51:09.063','2')
insert into @test-2 values ('GX,1,0000000000000000000000000','2013-12-17 16:51:15.257','4') --4
;with
GX as (
select *, row_number() over(order by ts) rn
from @test-2
where Data like 'GX%'
),
buckets as (
Select gx1.ts gxbegin, gx2.ts gxend, gx2.data gxdata, gx2.Tpkt_type gxtype
from GX gx1
right join gx gx2
on gx2.rn = gx1.rn+1
),
bucketed as (
select t.*, b.* from @test-2 t
join buckets b
on t.ts < b.gxend and (t.ts > b.gxbegin or b.gxbegin is null)
),
filtered as (
select t.*, b.gxdata, b.gxend, b.gxtype from buckets b
cross apply (
select top(1) * from @test-2 t
where t.ts < b.gxend
and (t.ts > b.gxbegin or b.gxbegin is null)
order by t.ts asc
) t
)
select * from filtered