2016-09-17 49 views
0

Image for SQL Table data如何鏈接的兒子與他的父親通過SQL語句

我在SQL Server表我想顯示的數據等:

  1. 史密斯
  2. 約翰遜史密斯
  3. 威廉姆斯史密斯
  4. Brown Johnson Smith
+1

哪個RDBMS是這個呢?請添加一個標籤來指定您是使用'mysql','postgresql','sql-server','oracle'還是'db2' - 或者其他的東西。 –

+0

你需要自己加入。 –

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 –

回答

3

如果S QL服務器(在公佈的圖像會)

Declare @Table table (ID int,CLevel int,CParent int ,Name varchar(50)) 
Insert into @Table values 
(1,1,NULL,'Smith'), 
(2,2,1 ,'Johnson'), 
(3,2,1 ,'Williams'), 
(7,3,2 ,'Brown') 


;with cteHB (ID,CParent,Lvl,Name,PathName) as (
    Select ID 
      ,CParent 
      ,Lvl=1 
      ,Name 
      ,PathName = cast(Name as varchar(500)) 
    From @Table 
    Where CParent is null 
    Union All 
    Select cteCD.ID 
      ,cteCD.CParent,cteHB.Lvl+1 
      ,cteCD.Name 
      ,PathName = cast(concat(cteCD.Name,' ',cteHB.PathName) as varchar(500)) 
    From @Table cteCD 
    Join cteHB on cteCD.CParent = cteHB.ID) 
Select A.ID 
     ,A.CParent 
     ,A.Lvl 
     ,A.Name 
     ,A.PathName 
From cteHB A 

返回

ID CParent Lvl Name  PathName 
1 NULL  1 Smith  Smith 
2 1  2 Johnson Johnson Smith 
3 1  2 Williams Williams Smith 
7 2  3 Brown  Brown Johnson Smith 
+0

謝謝,工作好你是天才 –