SQL 分组依据和列表中的 return 对

SQL Group By and return pairs from list

抱歉,如果标题与此内容不匹配。

我目前有一个数据库,其中包含时间表及其经过的地点列表。

HeaderId, LocationOrdinal, Location
1,0,A
1,1,B
1,2,C
1,3,D
1,4,E

2,0,A
2,1,B
2,2,F
2,3,G

我想让它们按 HeaderId 分组,让位置彼此相邻,然后区分。

Desired Output
A,B
B,C
C,D
D,E
B,F
F,G

请注意,A、B 只在其中一次。

我目前获取 table 中的所有值并通过 C# 完成,但速度很慢。

SELECT HeaderId, Location FROM [dbo].[sched_timings] ORDER BY HeaderId, LocationOrdinal

提前致谢

一种方法使用 join:

select distinct st.Location, stnext.Location
from sched_timings st join
     sched_timings stnext
     on stnext.HeaderId = st.HeaderId and
        stnext.LocationOrdinal = st.LocationOrdinal + 1;

另一种方法使用lead():

select distinct location, next_location
from (select st.*, 
             lead(location) over (partition by HeaderId order by LocationOrdinal) as next_location
      from sched_timings st
     ) st
where next_location is not null;