我能想到的另一种方法,在其他 RDBMS 上移植更容易:http ://www.sqlfiddle.com/#!4/da0a3/19
with parent(root_node, child_of, parent_id, depth) as
(
select id, id, parent_id, 1
from edition
union all
select p.root_node, e.id, e.parent_id, p.depth + 1
from edition e
join parent p on p.child_of = e.parent_id
)
select root_node, max(child_of)
from parent
where (root_node,depth) in
(select root_node,max(depth) from parent group by root_node)
group by root_node
order by root_node
输出:
| ROOT_NODE | MAX(CHILD_OF) |
-----------------------------
| 1 | 7 |
| 2 | 2 |
| 3 | 3 |
| 4 | 7 |
| 5 | 7 |
| 6 | 6 |
| 7 | 7 |
现在,我喜欢 Oracle(也喜欢http://sqlfiddle.com),它非常简洁。现在我知道 KEEP DENSE_RANK 中 MIN 和 MAX 的用途。而在此之前,我没有看到任何在 KEEP DENSE_RANK 中明确指定 MIN/MAX 的实用程序。现在我知道它有一个实用程序,如果在深度上有一些联系,你可以通过使用 MIN 和 MAX 来查看谁是第一个和最后一个。
例如http://www.sqlfiddle.com/#!4/da0a3/24
with parent(root_node, child_of, parent_id, depth) as
(
select id, id, parent_id, 1
from edition
union all
select p.root_node, e.id, e.parent_id, p.depth + 1
from edition e
join parent p on p.child_of = e.parent_id
)
select root_node,
min(child_of) keep(dense_rank last order by depth) as first_in_deepest,
max(child_of) keep(dense_rank last order by depth) as last_in_deepest
from parent
group by root_node;
| ROOT_NODE | FIRST_IN_DEEPEST | LAST_IN_DEEPEST |
--------------------------------------------------
| 1 | 6 | 7 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | 6 | 7 |
| 5 | 6 | 7 |
| 6 | 6 | 6 |
| 7 | 7 | 7 |