我有一个自我相关的表 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:深度可能会有所不同,这里是很小的例子
我有一个自我相关的表 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:深度可能会有所不同,这里是很小的例子
尝试:
SELECT id,
refid
FROM mytable t
WHERE NOT EXISTS (SELECT 1
FROM mytable
WHERE refid = t.id)
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
select ID, RefId
from myTable t1 left join myTable t2 on t1.ID = t2.RefID
where t2.RefID is null
尝试这个:
SELECT *
FROM
my_table
WHERE
id NOT IN
(
SELECT DISTINCT
refId
FROM
my_table
WHERE
refId IS NOT NULL
)