假设我有两个表:第一个表名为sales,有两个列名为product和quantity,第二个表名为nomenclature,有两个列名为compound和component。
每个compound都可以有几个components,而每个component本身可以是一个具有多个components的compound,这使得第二个表成为一个层次结构。让我们以下面的表格为例:
TABLE : SALES
PRODUCT - QUANTITY
P1 - 200
P2 - 300
F3 - 400
P5 - 500
TABLE : NOMENCLATURE
COMPOUND - COMPONENT
P1 - A1
P1 - B2
P2 - D4
A1 - F6
B2 - Q7
D4 - F8
Q7 - F9
F9 - H10
P3 - F11我希望为SALES.PRODUCT中的每一行查找其层次结构中以F开头的每个组件,如果产品本身以F开头或忽略该行,则返回它们和/或返回自己。最终结果应该如下所示:
PRODUCT - QUANTITY - COMPONENT
P1 - 200 - F6
P1 - 200 - F9
P2 - 300 - F8
F3 - 400 - F3
F3 - 400 - F11(P5被忽略了,因为它不是以F开头,也没有任何以F开头的子项)
如何用最有效的方法在PL/SQL (ORACLE)中获得这一结果(术语实际上有超过500 k行)
发布于 2016-06-13 14:31:41
你可以这样做:
WITH combined ( product, component, quantity ) AS (
SELECT product, product, quantity FROM sales
UNION ALL
SELECT compound, component, NULL FROM nomenclature
)
SELECT CONNECT_BY_ROOT( product ) AS product,
CONNECT_BY_ROOT( quantity ) AS quantity,
component
FROM combined
WHERE component LIKE 'F%'
START WITH quantity IS NOT NULL
CONNECT BY NOCYCLE PRIOR component = product;https://stackoverflow.com/questions/37790856
复制相似问题