2016-04-22 74 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

尽管你没有办法实现,但你给了我一种新的思考方式,我已经实现了,非常感谢。 –

相关问题