递归查询问题 - 将行分成列?

时间:2010-05-26 21:17:13

标签: sql sql-server-2000 recursive-query

我有一张桌子“家庭”,就像这样

FamilyID    PersonID    Relationship
-----------------------------------------------
F001        P001        Son
F001        P002        Daughter
F001        P003        Father
F001        P004        Mother
F002        P005        Daughter
F002        P006        Mother
F003        P007        Son
F003        P008        Mother

我需要输出

FamilyID    PersonID    Father  Mother
-------------------------------------------------
F001        P001        P003    P004
F001        P002        P003    P004
F001        P003        
F001        P004        
F002        P005                P006
F002        P006        
F003        P007                P008
F003        P008        

其中列出了给定PersonID的父亲和母亲的PersonID(如果适用)在单独的列中。我知道这必须是一个相对简单的查询(因此找到指令),但我似乎无法提出正确的搜索条件。搜索“SQL递归查询”让我最接近,但我无法将这些方法完全转化为我在这里要做的事情。

我正在努力学习,因此欢迎多种方法,我应该阅读的词汇也是如此。谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用外连接自行连接表两次以获得所需内容:

SELECT
    T1.FamilyID AS FamilyID,
    T1.PersonID AS PersonID,
    T2.PersonID AS Father,
    T3.PersonID AS Mother
FROM Families T1
LEFT JOIN Families T2
    ON T1.FamilyID = T2.FamilyID
   AND T1.Relationship IN ('Son', 'Daughter')
   AND T2.Relationship = 'Father'
LEFT JOIN Families T3
    ON T1.FamilyID = T3.FamilyID
   AND T1.Relationship IN ('Son', 'Daughter')
   AND T3.Relationship = 'Mother'

结果:

FamilyID  PersonID  Father  Mother  
F001      P001      P003    P004    
F001      P002      P003    P004    
F001      P003      NULL    NULL    
F001      P004      NULL    NULL    
F002      P005      NULL    P006    
F002      P006      NULL    NULL    
F003      P007      NULL    P008    
F003      P008      NULL    NULL    

答案 1 :(得分:0)

在SQL Server中,用于解决此类递归问题的功能是Common Table Expressions