Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL根据其他表中的行关系创建表_Sql_Sql Server - Fatal编程技术网

SQL根据其他表中的行关系创建表

SQL根据其他表中的行关系创建表,sql,sql-server,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都有一行,因此,输出如下所

需要帮助从下表使用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

如果您使用的是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;