如何在使用update的嵌套子查询中使用外部查询变量?

时间:2020-06-02 12:42:35

标签: sql oracle oracle11g sql-update

update fee_schedule fs set fs.branch_id=
(
SELECT  branch_id  FROM   (SELECT  branch_id
                                       ,updated_ts
                                       ,gr_number
                                      ,row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts desc) AS sno
                                FROM   admission_log ) x
                       WHERE  x.gr_number = fs.gr_number and to_char(x.updated_ts,'yyyymm') < fs.schedule_month
                       and rownum=1
                       order by sno
)
where fs.branch_id is null ;

SQL错误:ORA-00907:缺少右括号 00907. 00000-“缺少右括号”

我尝试使用的相同方法:

update fee_schedule fs set fs.branch_id=
(
select c.branch_id
      from (select b.branch_id,updated_ts,
                   row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
                   from admission_log b
                   where b.gr_number = fs.gr_number and to_char(b.updated_ts,'yyyymm') <  fs.schedule_month ) c
      where c.sno = 1
)
where fs.branch_id is null ;

我发现此错误:

SQL错误:ORA-00904:“ FS”。“ SCHEDULE_MONTH”:无效的标识符

1 个答案:

答案 0 :(得分:0)

您可以使用keep

update fee_schedule fs
    set fs.branch_id =
            (select max(b.branch_id) keep (dense_rank first order by updated_ts desc)
              from admission_log al
                   where al.gr_number = fs.gr_number and
                         to_char(al.updated_ts, 'yyyymm') < fs.schedule_month 
            )
where fs.branch_id is null ;

此结构等效于“ first()”聚合函数,可以轻松解决Oracle对相关子查询的范围限制。