如何找到最后一个孩子?

时间:2013-01-17 10:08:05

标签: sql-server-2008

我在SQL server中有以下表

    (id,name,parentId)
    (1,nilesh,NULL)
    (2,nikhil,1)    
    (3,nitin ,2)  
    (4,Ruchi,3)

    (5,xx,NULL)
    (6,YY,5)
    (7,ZZ,6)

我想找到每组中的最后一个孩子

result: (4,Ruchi,3),(7,ZZ,6)

怎么做?

1 个答案:

答案 0 :(得分:0)

SELECT  *
FROM    mytable m
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable mc
        WHERE   mc.parentId = m.id
        )

检查:

WITH    mytable AS
        (
        SELECT  *
        FROM    (
                VALUES
                (1,'nilesh',NULL),
                (2,'nikhil',1),   
                (3,'nitin' ,2),  
                (4,'Ruchi',3),
                (5,'xx',NULL),
                (6,'YY',5),
                (7,'ZZ',6)
                ) q (id, name, parentId)
        )
SELECT  *
FROM    mytable m
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable mc
        WHERE   mc.parentId = m.id
        )

---

4   Ruchi   3
7   ZZ  6