我有一个表格,其中包含所有文件夹的ID及其对应的父ID。
我想导出文件夹的所有父文件夹,但我需要将这些文件夹放在一列中。
我正在尝试使用数据透视表,但由于某种原因它不起作用。在线所有透视示例都包含聚合函数。我是否必须实施一个以便工作?我不认为我这样做。
SELECT * FROM
(SELECT F.Id, F1.Id, F2.Id, F3.Id, F4.Id, F5.Id, F5.ParentId
FROM Folder F
LEFT JOIN Folder F1 ON F1.Id = F.ParentId
LEFT JOIN Folder F2 ON F2.Id = F1.ParentId
LEFT JOIN Folder F3 ON F3.Id = F2.ParentId
LEFT JOIN Folder F4 ON F4.Id = F3.ParentId
LEFT JOIN Folder F5 ON F5.Id = F4.ParentId
WHERE F.Id = '65D33613-9476-4BC8-90AA-2DA622CAA7CD') AS Folders
UNPIVOT(
Idens FOR F.Id IN (Id)
) AS PivotTable
答案 0 :(得分:1)
您可以使用递归公用表表达式而不是UNPIVOT
。
;WITH CTE AS (
SELECT *, 1 RN FROM Folder WHERE Id = '65D33613-9476-4BC8-90AA-2DA622CAA7CD'
UNION ALL
SELECT F.Id, F.ParentID, RN+1 RN FROM Folder F INNER JOIN CTE ON F.Id = CTE.ParentID
)
SELECT 'Id_' + CONVERT(VARCHAR,RN) Idens , Id FROM CTE
UNION ALL
SELECT * FROM (SELECT TOP 1 'ParentId' Idens , Id FROM CTE ORDER BY RN DESC) AS Parent