2017-03-28 66 views
0

訂單數據我有一個表自反協會

enter image description here

此表代表一組技術和subtechnologies。一項技術可以包含n個子技術,一個技術包含1個子技術。

我需要訂購這一套這樣

enter image description here

我感謝你的幫助。

+0

秩序? –

+0

你想如何處理空值?該名字是應該訂購還是僅僅是巧合? – owczarek

+0

您需要遞歸CTE來計算層次路徑和按路徑排序。請參閱示例http://stackoverflow.com/questions/14241936/how-can-i-generate-a-hierarchy-path-in-sql-that-leads-to-a-given-node – Serg

回答

1

,這可能是你的問題的解決方案,而無需FK_idTecnFK,PK_idTecn使用遞歸CTE

DECLARE @T TABLE (IdTech INT, IdTechFK INT, Name VARCHAR(255)) 
INSERT INTO @T VALUES 
(1, NULL, 'FRT'), 
(2, 1, 'FRT_1'), 
(3, 1, 'FRT_2'), 
(4, NULL, 'GSC filters'), 
(5, 4, 'GSC filters_1'), 
(6, 4, 'GSC filter_2'), 
(7, 1, 'FRT_3'), 
(8, 1, 'FRT_4'), 
(9, NULL, 'Power Control') 

SELECT a.IdTech, a.IdTechFK, a.Name 
FROM (
SELECT m.IdTech, m.IdTechFK, m.Name, m.IdTech AS r FROM @T AS m 
WHERE m.IdTechFK IS NULL 
UNION ALL 
SELECT c.IdTech, c.IdTechFK, c.Name, c.IdTechFK AS r FROM @T AS c 
WHERE c.IdTechFK IS NOT NULL) AS a 
ORDER BY a.r, idtech, IdTechFK 

結果

+-------+---------+--------------+ 
|IdTech |IdTechFK |Name   | 
+-------+---------+--------------+ 
|1  |NULL  |FRT   | 
|2  |1  |FRT_1   | 
|3  |1  |FRT_2   | 
|7  |1  |FRT_3   | 
|8  |1  |FRT_4   | 
|4  |NULL  |GSC filters | 
|5  |4  |GSC filters_1 | 
|6  |4  |GSC filter_2 | 
|9  |NULL  |Power Control | 
+-------+---------+--------------+ 
+0

這隻能解決方案,如果遞歸沒有更多的一個級別。 – Serg

+0

@Serg:我同意這一點,我已將我的解決方案基於給定的數據 – Kevin