从下表CTE

时间:2019-10-21 19:18:54

标签: sql sql-server-2014

我有下表: dbo.split

Name  Time   
Alex  120
John  80 
John  300 
Mary  500
Bob   900

然后是另一个表dbo.travel

Name Time
Alex  150
Alex  160 
Alex  170
John  90
John  100
John  310  
Mary  550
Mary  600 
Mary  499 
Bob   800
Bob   700

对于表拆分中的每个值,我需要在表行程中查找下一个值。我尝试使用CTE a和ROW_NUMBER()进行分组,但是我无法按正确的值分组,因为dbo.split可以包含同一个名称的多个值。

我正在寻找以下输出:

Name  Time TravelTime 
Alex  120  150
John  80   90
John  300  310
Mary  500  550
Bob   900  NULL   

这是我到目前为止的内容,但是失败了,因为拆分表每人可以有多个记录:

;with result as (
 select t.*, 
 ROW_NUMBER() OVER (Partition BY t.Name order by t.Time) as rn 
 from travel t join split s 
 on t.Name = s.Name and t.TIME>s.Time
 )

2 个答案:

答案 0 :(得分:1)

我会使用apply

select s.*, t.time
from split s outer apply
     (select top (1) t.*
      from travel t
      where t.name = s.name and t.time > s.time
      order by t.time asc
     ) t;

在这种情况下,apply与相关子查询在本质上是一样的,因此您也可以用这种方式来表达它。

答案 1 :(得分:0)

您可以尝试以下操作

   Select * from(Select 
        Name,t.time,t1.time, 
       Row_number() over (partition by
        Name,t.time order by t1.time) rn
        from split t
       Join travel t1 on t.time <t1.time and 
          t.name =t1.name) 
          where 
           rn=1;