2016-04-22 133 views
-1

我可以使用遊標,但效率不高。有沒有更好的方法來使用SQL語句來獲得這些結果?SQL Server:如何使用SQL語句獲得想要的結果

表:一個

A1 ID  A2 
-------------------- 
aaa A  8:30 
bbb A  9:30 
ccc A  10:00 

表:乙

ID ​B2 
---------- 
A 8:30 
A 9:00 
A 9:10 
A 9:30 
A 9:50 
A 10:01 
A 12:00 

期望的結果:

ID B2 ​ ​A1 
--------------------- 
A 8:30 ​ ​aaa 
A 9:00 ​ ​aaa 
A 9:10 ​ ​aaa 
A 9:30 ​ ​bbb 
A 9:50 ​ ​bbb 
A 10:00 ​ ​bbb 
A 10:01  ccc  
A 12:00  ccc 
+2

A2和B2列的數據類型是什麼? – spencer7593

回答

0

雖然你沒有實現的方法,

因爲你的解釋是不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 
0

嗯。 。 。 。這需要組合這兩個表來創建行和列。有點棘手。行建議union。列建議別的東西,如join或相關子查詢:

select ab.id, ab.b2, 
     (select a.a1 
     from a 
     where a.a2 <= ab.b2 
     order by a.a2 desc 
     limit 1 
     ) as a1 
from ((select id, a2 as b2 from a) union 
     (select id, b2 from b) 
    ) ab; 
+0

儘管你沒有辦法實現,但你給了我一種新的思考方式,我已經實現了,非常感謝。 –