CTE上的功能是否计划用于SQL标准或当前的任何RDBMS中?像这样吗?
with strahler(node, sn) function(_parent int) as
(
select
s.node,
case
-- If the node is a leaf (has no children),
-- its Strahler number is one.
when count(st.*) = 0 then
1
when count(st.*) >= 2 then
case
-- If the node has one child with Strahler number i,
-- and all other children have Strahler numbers less than i,
-- then the Strahler number of the node is i again.
when min(st.sn) < max(st.sn) then
max(st.sn)
-- If the node has two or more children with Strahler number i,
-- and no children with greater number,
-- then the Strahler number of the node is i + 1.
when min(st.sn) = max(st.sn) then
max(st.sn) + 1
end
end
from streams s
left join lateral strahler(s.node) st on true
where _parent = 0 or s.to_node = _parent
group by s.node
)
select st.*, s.expected_order
from strahler(0) st
join streams s on st.node = s.node
order by st.node;
我很难为以下stackoverflow问题设计一个递归CTE解决方案:How to determine Strahler number on a directed graph for a stream network
请注意,如果单独创建功能,则概念化的“ CTE上的功能”将起作用。参见:https://www.db-fiddle.com/f/8z58LCVhD62YvkeJjriW8d/3
我想知道该解决方案是否可以仅使用纯CTE来完成,而无需编写函数。 I tried,但CTE无法对其进行左连接。
无论如何,我将在这里重新发布问题的性质。
CREATE TABLE streams (
node integer PRIMARY KEY,
to_node integer REFERENCES streams(node),
expected_order integer
);
INSERT INTO streams(node, to_node, expected_order) VALUES
(1, NULL, 4),
(2, 1, 4),
(3, 2, 3),
(4, 2, 3),
(5, 4, 3),
(6, 3, 2),
(7, 3, 2),
(8, 5, 2),
(9, 5, 2),
(10, 6, 1),
(11, 6, 1),
(12, 7, 1),
(13, 7, 1),
(14, 8, 1),
(15, 8, 1),
(16, 9, 1),
(17, 9, 1),
(18, 4, 1),
(19, 1, 1);
使用以下算法(源自wikipedia)从该数据中获取数据...
在这种情况下,所有树木都是有向图,从根到叶的方向;换句话说,它们是树状结构。树中节点的度数就是其子级数。可以按照自下而上的顺序将Strahler编号分配给树的所有节点,如下所示:
...这是产生的:
请参见上方的字段expected_order
,应用该算法时每个节点的strahler order number
。