使用自反关联订购数据

时间:2017-03-28 09:31:52

标签: sql sql-server

我有一张桌子

enter image description here

此表代表一组技术和子技术。一项技术可以包含n个子技术,并且一个tecn包含1个subtecn。

我需要像这样订购这套

enter image description here

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这可能是您的问题的解决方案,而不使用递归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 |
+-------+---------+--------------+