雖然你沒有實現的方法,
因爲你的解釋是不enough.you應該解釋爲什麼9:30是BBB,爲什麼 10:00爲BBB
我嘗試使用SQL Server 2012+
declare @t table(A1 varchar(50),ID varchar(50), A2 time)
insert into @t values
('aaa','A','8:30')
,('bbb','A','9:30')
,('ccc','A','10:00')
--select *,LEAD(A2,1)over(order by id) A2_EndTime from @t
declare @t1 table(ID varchar(50), B2 time)
insert into @t1 values
('A','8:30')
,('A','9:00')
,('A','9:10')
,('A','9:30')
,('A','9:50')
,('A','10:01')
,('A','12:00')
;With CTE as
(
select *,LEAD(A2,1)over(order by id) A2_EndTime from @t
)
--select * from cte
,CTE1 as
(select t1.ID,t1.B2
from @t1 t1
)
,CTE2 as
(
select * from @t c where not exists(select b2 from cte1 c1 where c1.b2=c.a2)
)
,cte3 as
(
select id,b2 from cte1
union all
select id,a2 from cte2
)
select t1.ID,t1.B2
,(select top 1 t.A1 from CTE t where ((t.A2_EndTime is null and t1.b2>=t.a2)
or (t.A2_EndTime is not null and (t1.b2 >= t.a2 and t1.b2< t.A2_EndTime))))
from cte3 t1
A2和B2列的數據類型是什麼? – spencer7593