我正在使用sql server 2008在asp.net上开发Family tree应用程序。
我的主表是这样的: -
ID int PK
Name Varchar(50)
MotherID int
FatherID int
ID MotherID FatherID Name
1 NULL NULL My Grand Father
2 NULL NULL My Grand Mother
3 someid someid My Mother
4 2 1 My Father
5 3 4 Me
6 someid someid My wife
7 3 4 My Brother
8 6 5 My son.
我正在寻找像这样的输出
ID MotherID FatherID Name Level
1 someid someid grandfather 0
2 someid someid Father 1
3 someid someid Me 2
4 someid someid Brother 2
5 someid someid My Son 3
提前致谢。 克什米尔。
答案 0 :(得分:2)
试试这个:
;WITH FamilyCTE
AS
(
SELECT
*,
CAST(NULL AS VARCHAR(50)) AS FatherName,
CAST(NULL AS VARCHAR(50)) AS MotherName, 0 AS Level
FROM @FamilyTree
WHERE FatherID IS NULL
AND MotherID IS NULL
UNION ALL
SELECT
f.ID,
f.Name AS ParentName,
f.MotherID,
f.FatherID,
c.Name AS FatherName,
c2.Name AS MotherName,
Level + 1
FROM @FamilyTree AS F
INNER JOIN FamilyCTE c ON F.FatherID = c.ID
INNER JOIN @FamilyTree c2 ON f.MotherID = c2.ID
)
SELECT * FROM FamilyCTE
如果想要获得与您在问题中发布的内容一样的确切输出,请忽略FatherName
和MotherName
,并将SELECT * FROM FamilyCTE
中的选择限制为您要选择的列,例如,使用WHERE ID = 1
在锚点查询中使用起始祖父。如以下演示:
答案 1 :(得分:0)
select t1.ID, t1.MotherID,
t1.FatherID,
t1.name,
t2.Name,
Level
from table1 t1
left outer join table2 t2 on t1.FatherID =t2.FatherID