Sql 查询以获取祖父母和孙辈

Sql 查询以获取祖父母和孙辈,sql,sql-server,Sql,Sql Server,我有一张桌子,人: ID name surname mother_id father_id -------------------------------------------- 1 John smith null null 2 kate m null null 3 philip smith 2 1 4 dimitr smith 7

我有一张桌子,

ID   name    surname   mother_id  father_id
--------------------------------------------
1    John    smith     null       null
2    kate    m         null       null
3    philip  smith        2         1
4    dimitr  smith        7         3
等等

我试过这个问题

SELECT 
    p.name, P.surname, 
    c.name as 'Mothers name', c.surname as 'Mothers surname',  
    gm.name as 'Grandmother name', gm.surname as 'Grandmother surname'
FROM
    dbo.people AS p
JOIN
    dbo.people AS c ON (c.mother = p.Id)
JOIN
    dbo.people AS gm ON (gm.mother = c.Id)

但它并没有真正返回我所期望的

关于子句的问题:

select p.name, p.surname, 
       coalesce(pm.name, '') as mothername, coalesce(pm.surname, '') as mothersurname,
       coalesce(pf.name, '') as grandmothername, 
       coalesce(pf.surname, '') as grandmothersurname
from people p left join
     people pm
     on pm.id = p.mother_id left join -- use mother_id from people p
     people pf
     on pf.id = p.father_id; -- use father_id from people p;

这是

编辑问题并添加预期结果。Yogesh关于连接列的交换是正确的。您可以在db fiddle上查看和使用解决方案