【问题标题】:Hierarchical Query Using Connect By使用 Connect By 的分层查询
【发布时间】:2015-11-04 20:31:35
【问题描述】:

以下是与我的真实场景相似的示例上下文。

产品:XYZ QTY:1

需要原材料B,0.002 和半成品A,0.001。生产 A 我需要原材料J,0.1 和半成品K,0.9。有产品 K I 之前我需要原材料 G 0.004 enter code hereT 0.005

我需要获得生产10 的产品数量XYZ 的累计所需所有原材料的结果。

【问题讨论】:

  • 解决方案是否需要使用CONNECT BY?使用递归 WITH 子句会更自然。
  • 我认为这是一个很好的问题,但它被否决了,因为标题非常笼统,而且问题难以阅读。另外,在您澄清是否真的需要使用 CONNECT BY 之前,我不会进一步研究解决方案(即您使用的 Oracle 是否低于 11gR2?)

标签: sql oracle oracle-ebs


【解决方案1】:

试试这个:

SELECT component AS material, 10 * quantity AS quantity
  FROM (SELECT component, quantity,
               CASE WHEN CONNECT_BY_ISLEAF = 1 THEN 'Raw' ELSE 'Semi-Finished' END AS type
     FROM bill_of_materials
    START WITH item = 'XYZ' CONNECT BY PRIOR component = item)
 WHERE type = 'Raw'

SQL Fiddle 上的示例给出:

J |        1
G |     0.04
T |     0.05
B |     0.02

【讨论】:

  • 我忘记了将因子乘以树。明天会重新考虑。
【解决方案2】:

@KenGeis 在 cmets 中提到,对于 Oracle 11g,您可以使用递归查询:

with t (p, i , q) as (
  select product, ingredient, qty from test where product = 'XYZ'
  union all 
  select product, ingredient, qty*q from test, t where product = i)
select i, sum(q) qty from t 
  where not exists (select 1 from test where product = i) group by i;

如果由于某些原因您需要connect by 版本,这是我的尝试:

with t1 as (
  select ingredient i, sys_connect_by_path(ingredient, '/') path1, 
         sys_connect_by_path(qty, '/') path2
    from test where connect_by_isleaf = 1 connect by prior ingredient = product
    start with product = 'XYZ' ),
t2 as (
  select i, path1, path2, trim(regexp_substr(path2, '[^/]+', 1, lines.column_value)) val
    from t1,
      table (cast (multiset(
        select level from dual connect by level < regexp_count(t1.path2, '/')+1
        ) as sys.ODCINumberList ) ) lines)
select i, sum(s) qty
  from (select i, exp(sum(ln(val))) s from t2 group by i, path1) group by i

SQL Fiddle demo for both queries

子查询t1 生成所需原料的列表,并在列 path2 中 - 我们需要相乘的因素。 t2 unpivots 这些值,最终查询执行乘法并对结果进行分组,以防万一 是两个使用相同原材料的半成品。 对于乘法,我使用了来自this SO 问题的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2019-10-07
    • 2015-04-25
    相关资源
    最近更新 更多