5

我有一个自我相关的表 myTable,例如:

ID | RefID
----------
 1 | NULL
 2 | 1
 3 | 2
 4 | NULL
 5 | 2
 6 | 5
 7 | 5
 8 | NULL
 9 | 7

我需要得到任何深度的叶子行

根据上表,结果必须是:

ID | RefID
----------
 3 | 2
 4 | NULL
 6 | 5
 8 | NULL
 9 | 7

谢谢你

PS:深度可能会有所不同,这里是很小的例子

这是示例数据的可视化演示

4

4 回答 4

8

尝试:

SELECT id,
       refid
FROM   mytable t
WHERE  NOT EXISTS (SELECT 1
                   FROM   mytable
                   WHERE  refid = t.id)  
于 2013-05-20T15:06:36.273 回答
7
DECLARE @t TABLE (id int NOT NULL, RefID int NULL);

INSERT @t VALUES (1, NULL), (2, 1),  (3, 2),  (5, NULL), 
             (6, 5), (4, NULL), (7, 5), (8, NULL), (9, 8), (10, 7);

WITH CTE AS
(
    -- top level
    SELECT id, RefID, id AS RootId, 0 AS CTELevel FROM @t WHERE REfID IS NULL
    UNION ALL
    SELECT T.id, T.RefID, RootId, CTELevel + 1 FROM @t T JOIN CTE ON T.RefID = CTE.id
), Leafs AS
(
    SELECT
        id, RefID, DENSE_RANK() OVER (PARTITION BY CTE.RootId ORDER BY CTELevel DESC) AS Rn
    FROM CTE
)
SELECT
    id, RefID
FROM
    Leafs
WHERE
    rn = 1
于 2013-05-20T15:15:28.223 回答
3
select  ID, RefId
from    myTable t1 left join myTable t2 on t1.ID = t2.RefID
where   t2.RefID is null
于 2013-05-20T15:06:48.650 回答
0

尝试这个:

SELECT *
FROM
     my_table
WHERE
     id NOT IN
     (
      SELECT DISTINCT
         refId
      FROM
         my_table
      WHERE
         refId IS NOT NULL
      )
于 2019-05-21T14:22:13.297 回答