Oracle SQL-多级相关子查询不起作用
我试图运行一个UPDATE语句,其中包含引用更新表的两级子查询,但出现了一个错误。 请考虑以下代码。它给了我c.end_date无效标识符错误,就好像表c更新的表在最深的子查询中不可见一样。 如果我将子查询展平到只有一个级别的子查询,我就会失去它背后的逻辑 有没有关于如何编写它以使其正确编译和工作的想法 我使用的是Oracle Database 10g Enterprise Edition 10.2.0.3.0版-ProdOracle SQL-多级相关子查询不起作用,sql,oracle,subquery,correlated-subquery,Sql,Oracle,Subquery,Correlated Subquery,我试图运行一个UPDATE语句,其中包含引用更新表的两级子查询,但出现了一个错误。 请考虑以下代码。它给了我c.end_date无效标识符错误,就好像表c更新的表在最深的子查询中不可见一样。 如果我将子查询展平到只有一个级别的子查询,我就会失去它背后的逻辑 有没有关于如何编写它以使其正确编译和工作的想法 我使用的是Oracle Database 10g Enterprise Edition 10.2.0.3.0版-Prod create table calc( agrmt_id number
create table calc(
agrmt_id number,
cust_num number,
prod_id number,
price number,
start_date date,
end_date date);
create table trans(
agrmt_id number,
cust_num number,
prod_id number,
units number,
trans_date date);
create table products(
prod_id number,
other_prc number,
prod_start date,
prod_end date);
update calc c set price = (with avg_price_per_prod as (select prod_id, avg(other_prc) avg_prc
from products
where prod_end >= c.start_date
and prod_start <= c.end_date
group by prod_id
) select sum(t.units) * a.avg_prc
from trans t, avg_price_per_prod a
where t.trans_date between c.start_date and c.end_date
and t.agrmt_id=c.agrmt_id
and t.cust_num=c.cust_num
and t.prod_id = a.prod_id
);
不能在子查询中引用已更新的表c。你必须消除它,也许像这样未经测试的东西:
update calc c set price = (
select sum(t.units) * avg(other_prc)
from trans t, products p
where t.trans_date between c.start_date and c.end_date
and t.trans_date between p.prod_start and p.prod_end
and t.prod_id = p.prod_id
and t.agrmt_id=c.agrmt_id
and t.cust_num=c.cust_num
)