【问题标题】:Oracle SQL - multi-level correlated subquery does not workOracle SQL - 多级相关子查询不起作用
【发布时间】:2011-06-28 15:45:22
【问题描述】:

我正在尝试运行包含 2 级子查询的 UPDATE 语句,这些子查询引用更新后的表,但出现错误。 请考虑以下代码。它给了我“c.end_date 无效标识符”错误,好像表 c(更新的表)在最深的子查询中不可见。 如果我将子查询展平为仅一级子查询,我就会失去其背后的逻辑。

关于如何编写它以便编译和正常工作的任何想法?

我正在使用 Oracle 数据库 10g 企业版版本 10.2.0.3.0 - 产品

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
              ); 

【问题讨论】:

    标签: sql oracle subquery correlated-subquery


    【解决方案1】:

    您不能在子子查询中引用更新的表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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多