从下一个 table CTE 获取每个值的下一个值
Get next value for each of values from next table CTE
我有以下 table:
dbo.split
Name Time
Alex 120
John 80
John 300
Mary 500
Bob 900
然后是另一个tabledbo.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
对于 table split 中的每个值,我需要在 table travel 中找到下一个值。我尝试使用带有 ROW_NUMBER() 的 CTE a 来按组获取下一个,但我无法按正确的值进行分组,因为 dbo.split 可以包含相同名称的多个值。
我正在寻找以下输出:
Name Time TravelTime
Alex 120 150
John 80 90
John 300 310
Mary 500 550
Bob 900 NULL
这是我目前所拥有的,但它失败了,因为拆分 table 每个人可以有多个记录:
;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
)
我会用 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
与相关子查询的作用基本相同,因此您也可以这样表述。
您可以尝试如下
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;
我有以下 table: dbo.split
Name Time
Alex 120
John 80
John 300
Mary 500
Bob 900
然后是另一个tabledbo.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
对于 table split 中的每个值,我需要在 table travel 中找到下一个值。我尝试使用带有 ROW_NUMBER() 的 CTE a 来按组获取下一个,但我无法按正确的值进行分组,因为 dbo.split 可以包含相同名称的多个值。
我正在寻找以下输出:
Name Time TravelTime
Alex 120 150
John 80 90
John 300 310
Mary 500 550
Bob 900 NULL
这是我目前所拥有的,但它失败了,因为拆分 table 每个人可以有多个记录:
;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
)
我会用 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
与相关子查询的作用基本相同,因此您也可以这样表述。
您可以尝试如下
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;