我有脚本问题。请帮忙

时间:2014-03-20 15:29:22

标签: sql sql-server loops recursion common-table-expression

我写这篇文章,我有这种表结构。

CREATE TABLE #TEMP 
(
 IdNode varchar(5), 
 IdSubNode varchar(5), 
 Lvl int 
)

INSERT INTO #TEMP VALUES ('A', null,0), ('A','B',1), ('A','C',1), ('A','D',1)
INSERT INTO #TEMP VALUES ('B','B1',2), ('B','B2',2), ('B','B3',2)
INSERT INTO #TEMP VALUES ('D','D1',2), ('D','D2',2), ('D','D3',2)
INSERT INTO #TEMP VALUES ('B1','BB1',3), ('B1','BB2',3), ('B1','BB3',3)

SELECT * FROM #TEMP

拜托,我需要这样的查询:

/* -- I need this format
A / 
  / B /
      / B1 
           / BB1
           / BB2
           / BB3
      / B2 
      / B3
  / C /
  / D /
      / D1 
      / D2 
      / D3
*/

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?

SELECT DISTINCT *
FROM
(
SELECT DISTINCT IdNode AS '1st_Level'
FROM #TEMP
WHERE LEN(IdNode)=1
UNION ALL
SELECT DISTINCT IdSubNode AS '1st_Level'
FROM #TEMP
WHERE LEN(IdSubNode) = 1)A

LEFT JOIN
(SELECT DISTINCT IdNode AS '2nd_Level'
FROM #TEMP
WHERE LEN(IdNode)=2
UNION ALL
SELECT DISTINCT IdSubNode AS '2nd_Level'
FROM #TEMP
WHERE LEN(IdSubNode) = 2)B
ON A.[1st_Level] = LEFT(B.[2nd_Level],1)

LEFT JOIN
(SELECT DISTINCT IdNode AS '3rd_Level'
FROM #TEMP
WHERE LEN(IdNode)=3
UNION ALL
SELECT DISTINCT IdSubNode AS '3rd_Level'
FROM #TEMP
WHERE LEN(IdSubNode) = 3)C
ON LEFT(B.[2nd_Level],1) = LEFT(C.[3rd_Level],1)