昨天在论坛提了个问,有位朋友写了如下代码,今天想把这段弄成ORACLE的,弄不出来呀。来求助一下。。
create table tb(工艺序号 int,投入量 int,转换率 int)
insert into tb select 1,20,1
insert into tb select 2, 0,2
insert into tb select 3, 0,1
insert into tb select 4,10,2
insert into tb select 5, 0,3
insert into tb select 6, 5,2
go
;with cte as(
select *,投入量*转换率 as 应产出量 from tb where 工艺序号=1
union all
select b.*,(b.投入量+a.应产出量)*b.转换率 from cte a inner join tb b on a.工艺序号=b.工艺序号-1
)
select * from cte
/*
工艺序号        投入量         转换率         应产出量
----------- ----------- ----------- -----------
1           20          1           20
2           0           2           40
3           0           1           40
4           10          2           100
5           0           3           300
6           5           2           610(6 行受影响)*/
go
drop table tb

解决方案 »

  1.   

    其实可以自己试着修改一下,语法差不多吧!
    create table tb(工艺序号 int,投入量 int,转换率 int)
    insert into tb select 1,20,1
    insert into tb select 2, 0,2
    insert into tb select 3, 0,1
    insert into tb select 4,10,2
    insert into tb select 5, 0,3
    insert into tb select 6, 5,2
    go
    ;with cte as(
    select tb.*,投入量*转换率  应产出量 from tb where 工艺序号=1
    union all
    select b.*,(b.投入量+a.应产出量)*b.转换率 from cte a inner join tb b on a.工艺序号=b.工艺序号-1
    )
    select * from cte
    go
    drop table tb
    1、* 要指定表前缀。
    2、去掉列别名的as试试看看行不行,有错误提示再说。
      

  2.   

    不是这里的错误
    是在union all下面的select里引用了with 的cte临时表。。
    oralce里提示非法引用。union all
    select b.*,(b.投入量+a.应产出量)*b.转换率 from cte a inner join tb b on a.工艺序号=b.工艺序号-1
    --是这句错了不知道怎么改
      

  3.   

    临时表分两种,根据SESSION和TRANSACTION分。
    CREATE GLOBAL TEMPORARY TABLE table_name ON COMMIT PRESERVE ROWS.
    在SESSION结束是自动删除。
    CREATE GLOBAL TEMPORARY TABLE table_name ON COMMIT DELETE ROWS
    在提交COMMIT命令时候自动删除。也是从其他地方找来的。。
      

  4.   

    这个是cte的递归调用,你搜索下oracle的通用表达式用法!
      

  5.   

    oracle的sql中就不支持用with(cte)来替代connect by的递归查询。  
    所以你这样写
    union all
    select b.*,(b.投入量+a.应产出量)*b.转换率 from cte a inner join tb b on a.工艺序号=b.工艺序号-1
    是不对的,这里from cte就是递归查询了,所以LZ你可以搜索下oracle connect by递归查询。