我在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)
怎么做?
答案 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