我有一张表格如下:
ID | ChildsID | Name ----------------------- 1 NULL Name1 2 1 Name2 3 2 Name3 4 3 Name4 5 4 Name5 6 5 Name6 7 6 Name7 8 7 Name8 9 8 Name9 10 9 Name10 11 3 Name11
现在我想要一个查询,它可以为每个至少有一个子项的记录获取所有可能的子项,并返回一个像这样的DataSet:
ID | ParentID | Name | ParentIDs ----------------------------------------- 1 NULL Name1 11,10,9,8,7,6,5,4,3,2 2 1 Name2 11,10,9,8,7,6,5,4,3 3 2 Name3 11,10,9,8,7,6,5,4 4 3 Name4 10,9,8,7,6,5 5 4 Name5 10,9,8,7,6 6 5 Name6 10,9,8,7 7 6 Name7 10,9,8 8 7 Name8 10,9 9 8 Name9 10
答案 0 :(得分:4)
使用此查询。
更新结果 Fiddler Demo
CREATE TABLE TABLE1 (ID INT, ParentID INT, NAME VARCHAR(10));
INSERT INTO TABLE1 VALUES(1, NULL, 'Name1');
INSERT INTO TABLE1 VALUES(2, 1, 'Name2');
INSERT INTO TABLE1 VALUES(3, 2, 'Name3');
INSERT INTO TABLE1 VALUES(4, 3, 'Name4');
INSERT INTO TABLE1 VALUES(5, 4, 'Name5');
INSERT INTO TABLE1 VALUES(6, 5, 'Name6');
INSERT INTO TABLE1 VALUES(7, 6, 'Name7');
INSERT INTO TABLE1 VALUES(8, 7, 'Name8');
INSERT INTO TABLE1 VALUES(9, 8, 'Name9');
INSERT INTO TABLE1 VALUES(10, 9, 'Name10');
INSERT INTO TABLE1 VALUES(11, 3, 'Name11');
SELECT ID, ParentID , Name, Child = STUFF((
SELECT ',' + CAST(B.ID AS VARCHAR(100)) FROm TABLE1 AS B
WHERE ISNULL(A.ID, 0) < B.ID AND B.ID NOT IN(
ISNULL((SELECT TOP 1 C.ID FROm TABLE1 AS C
WHERE C.ParentID IN (
SELECT ParentID FROM TABLE1 WHERE ID <= A.ID)
ORDER BY C.ID DESC), 0))
ORDER BY B.ID DESC
FOR XML PATH (''), type).value('.', 'varchar(max)'), 1,1,'')
FROm TABLE1 AS A
旧结果:
SELECT ID, ParentID , Name, ParentIDs = STUFF((
SELECT ',' + CAST(B.ID AS VARCHAR(100)) FROm MyTable AS B
WHERE ISNULL(A.ID, 0) < B.ID ORDER BY B.ID DESC FOR XML PATH (''), type).value('.',
'varchar(max)'), 1,1,'')
FROm MyTable AS A
答案 1 :(得分:2)
你可以尝试使用这个:
SELECT a.*,x.ParentIDs
FROM YourTable a
CROSS APPLY (SELECT STUFF(CAST((SELECT ',' + CONVERT(VARCHAR,b.ID)
FROM YourTable b WHERE b.ID > a.ID AND ISNULL(b.ParentID,0) > ISNULL(a.ParentID,0) ORDER BY ID DESC
FOR XML PATH(''), TYPE) AS VARCHAR(MAX)),1,1,'') AS ParentIDs ) x
WHERE x.ParentIDs IS NOT NULL