SQL重新格式化链接列表(位置列表:节点 - >边缘)

时间:2013-06-29 17:27:05

标签: sql-server

希望你能通过提供一些语法来帮助我。

我正在尝试重新格式化:

id1 id2     pathType   location  
1   1   start   AlgonacPark
2   1   move    DuckLakePark
3   1   move    ClearLakePark
4   1   finish  GrandLakePark
5   2   start   CraigLakePark
6   2   finish  HayesPark

进入这个:

1   NULL    AlgonacPark
1   AlgonacPark DuckLakePark
1   DuckLakePark    ClearLakePark
1   ClearLakePark   GrandLakePark
1   GrandLakePark   NULL
2   NULL    CraigLakePark
2   CraigLakePark   HayesPark
2   HayesPark   NULL

逻辑相对简单......

(a。)使用id2

创建一组组

对于每个小组,

(b。)if pathType = start - > (id2,NULL,位置)

(c1。)制作一个有序的位置列表,使用'id1'来排序列表。

(c2。)使用循环成对输出列表 - > (id2,location1,location2)

示例:

2个位置:(1,2) - > (1,2)

3个位置:(1,2,3) - > (1,2),(2,3)

4个位置:(1,2,3,4) - > (1,2),(2,3),(3,4)

n个位置,其中(n> 1):( 1,...,n) - > (1,2),...,(n-1,n)

(d。)if pathType = finish - > (id2,location,NULL)

非常感谢!

1 个答案:

答案 0 :(得分:2)

尝试以下query.it将正常工作。

 WITH TEMP
 AS
 (
 SELECT ROW_NUMBER() OVER(PARTITION BY ID2 ORDER BY ID1) AS ID , *
 FROM LOCATION
 )
 SELECT A.ID1, A.ID2 , B.LOCATION , A.LOCATION 
 FROM TEMP AS A LEFT OUTER JOIN TEMP AS B ON A.ID -1 = B.ID AND A.ID2 = B.ID2
 UNION ALL 
 SELECT A.ID1,A.ID2 , A.LOCATION , NULL
 FROM TEMP AS A 
 WHERE PATHTYPE = 'FINISH'
 ORDER BY ID1

sqlFiddle