我有父/子矩阵
Parent_col_ID Child_col_ID
1 2
2 3
3 4
3 5
我需要将其修改为
Main_Parent Child1 Child2 Child3
1 2 3 4
1 2 3 5
如何在sql中执行此操作?
答案 0 :(得分:0)
您可以使用LEFT JOIN
和NOT EXISTS()
。这是您的查询:
--DROP TABLE CollEgues
--GO
CREATE TABLE CollEgues
(
Parent_col_ID int
,Child_col_ID int
);
INSERT INTO CollEgues VALUES(1,2),(2,3),(3,4),(3,5);
SELECT Main.Parent_col_ID AS Main_Parent
,Main.Child_col_ID AS Child1
,Child1.Child_col_ID AS Child2
,Child2.Child_col_ID AS Child3
FROM CollEgues AS Main
LEFT JOIN CollEgues AS Child1 ON Main.Child_col_ID = Child1.Parent_col_ID
LEFT JOIN CollEgues AS Child2 ON Child1.Child_col_ID = Child2.Parent_col_ID
WHERE NOT EXISTS (SELECT 1 FROM CollEgues C WHERE Main.Parent_col_ID=C.Child_col_ID);