-3

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

产品:XYZ QTY:1

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

我需要得到一个总需要所有原材料的结果,以及它的累积数量来生产10产品数量XYZ

4

2 回答 2

1

正如@KenGeis 在评论中提到的,对于 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 演示

子查询t1生成所需原料的列表和列 path2 - 我们需要相乘的因素。 t2 取消透视这些值,最终查询执行乘法并对结果进行分组,以防有两个使用相同原材料的半成品。对于乘法,我使用了这个SO question 的答案。

于 2015-11-04T12:31:35.697 回答
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
于 2015-11-03T05:19:37.730 回答