JOINING Same Table提供重复信息

时间:2013-03-18 05:24:21

标签: sql sql-server sql-server-2008 join

我想加入同一张表来获取一些信息。

我有人员表

PersonId, FirstName, LastName, Address

患者表

  

PatientId,PersonId,ResponsiblePersonId

以下是我试图获取患者名字的姓名,姓氏也是负责人名字,姓氏。对于这个我加入人员表再次获得负责人,姓氏。

但我收到了许多重复记录。

SELECT   PAT.PatientId

        ,PER.PersonNumber
        ,PER.FirstName
        ,PER.LastName
        ,RES_PER.FirstName AS ResFirstName
        ,RES_PER.LastName AS ResLastName
        ,PER.Address                

FROM        dbo.Patient AS PAT
INNER JOIN  dbo.Person AS PER
    ON  PAT.PersonId = PER.PersonId
INNER JOIN  dbo.Person AS RES_PER
    ON  PAT.ResponsiblePersonId = PER.PersonId

我如何获得患者名字,姓氏和姓名;负责人的名字,患者记录的姓氏?

2 个答案:

答案 0 :(得分:1)

基本上,您需要在表Person上连接两次表Patient,以便在其上获取两个相关列。

SELECT  b.FirstName Patient_FirstName, 
        b.LastName Patient_LastName,  
        b.Address Patient_Address,
        c.FirstName Responsible_Firstname, 
        c.LastName Responsible_LastName, 
        c.Address Responsible_Address
FROM    Patient a
        INNER JOIN Person b
            ON a.PersonID = b.PersonID
        INNER JOIN Person c
            ON a.ResponsiblePersonId = c.PersonID

要进一步了解联接,请访问以下链接:

答案 1 :(得分:1)

您需要做的就是在SQL的最后一位用PER替换RES_PER。 (即PER.PersonId变为RES_PER.PersonId)。

SELECT   PAT.PatientId
        ,PER.PersonNumber
        ,PER.FirstName
        ,PER.LastName
        ,RES_PER.FirstName AS ResFirstName
        ,RES_PER.LastName AS ResLastName
        ,PER.Address                

FROM        dbo.Patient AS PAT
INNER JOIN  dbo.Person AS PER
    ON  PAT.PersonId = PER.PersonId
INNER JOIN  dbo.Person AS RES_PER
    ON  PAT.ResponsiblePersonId = RES_PER.PersonId