1

我想加入同一张桌子以获取一些信息。

我有一个人表

PersonId, FirstName, LastName, Address

还有病人表

PatientId、PersonId、ResponsiblePersonId

以下是我尝试获取患者名字、姓氏以及负责人名字、姓氏的查询。为此,我再次加入 Person 表以获取责任人的名字和姓氏。

但是我有很多重复的记录。

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

如何获取患者记录的患者名字、姓氏和负责人的名字、姓氏?

4

2 回答 2

1

基本上,您需要在 tablePerson上连接 table 两次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

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-03-18T05:27:12.560 回答
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
于 2013-03-18T05:36:06.103 回答