SQL Server:如何使用SQL语句获得所需的结果

时间:2016-04-22 02:39:00

标签: sql sql-server

我可以使用游标,但效率低下。有没有更好的方法来使用SQL语句来获得这些结果?

表:A

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

表:B

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

  

虽然你没有办法实现,

因为你的解释还不够。你应该解释为什么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