SQL基于其他表中的行关系创建表

时间:2017-12-15 14:15:45

标签: sql sql-server

需要帮助使用下表中的SQL(SQL Server)创建一个沿袭表

Path ID  |  Sequence ID 
1            ad-1
1            ad-2
1            ad-3
2            ad-1
2            ad-4
3            ad-5
3            ad-6
3            ad-7
3            ad-8

预期的输出表在路径中的每对序列ID都有一行,因此,输出看起来像

Path        |     Source Seq ID |     Target Seq ID
1                 ad-1                ad-2
1                 ad-2                ad-3
2                 ad-1                ad-4
3                 ad-5                ad-6
3                 ad-6                ad-7
3                 ad-7                ad-8

1 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2012 +:

WITH VTE AS (
    SELECT *
    FROM (VALUES (1,'ad-1'),
                 (1,'ad-2'),
                 (1,'ad-3'),
                 (2,'ad-1'),
                 (2,'ad-4'),
                 (3,'ad-5'),
                 (3,'ad-6'),
                 (3,'ad-7'),
                 (3,'ad-8')) V(PathID, SequenceID)),
Targets AS (
    SELECT PathID,
           SequenceID,
           LEAD(SequenceID) OVER (PARTITION BY PathID ORDER BY SequenceID ASC) AS TargetSequenceID
    FROM VTE)
SELECT *
FROM Targets
WHERE TargetSequenceID IS NOT NULL;