2

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

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 递归查询”让我最接近,但我无法将这些方法完全转化为我在这里尝试做的事情。

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

4

2 回答 2

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    
于 2010-05-26T21:22:28.023 回答
0

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

于 2010-05-26T21:20:55.730 回答