with sql查询在约束with表的列时出错

zmeyuzjn  于 2021-08-09  发布在  Java
关注(0)|答案(4)|浏览(359)

这个查询有什么问题(甲骨文)

with latestplans as (
    select plan_id, max(plan_last_changed_date) 
    from idp.trainee_search_vw 
    group by plan_id 
)
select plan_id, training_organization 
from idp.trainee_search_vw 
where plan_id in (latestplans.plan_id);

错误是:
ora-00904编号: "LATESTPLANS"."PLAN_ID": invalid identifier 我正在定义一个临时表,其中包含视图中的一列和另一个最大分组的列。然后,我需要选择temp表的列。
目标是仅为最新计划选择某些属性,而视图最初列出所有计划。
内部查询工作正常。

lstz6jyr

lstz6jyr1#

你需要一个 select :

plan_id in (select latestplans.plan_id from latestplans);

CTE的行为类似于表或视图名称。你不能只使用它们而不引用它们 from 条款。

iugsix8n

iugsix8n2#

在你的询问中,你没有提到 latestplans 以你的观点 trainee_search_vw .

with latestplans as 
  (    select plan_id, max(plan_last_changed_date) from idp.trainee_search_vw 
group by plan_id )
select plan_id, training_organization 
from idp.trainee_search_vw as vw 
where exists (select 1 from latestplans where vw.plan_id=latestplans.plan_id);
fhity93d

fhity93d3#

它已经解释了您使用cte的方式有什么问题。
不过,我要指出:
您的查询似乎不像您描述的那样:外部查询应该在最长日期而不是最短日期进行过滤 plan_id ; 实际上,查询返回表中的所有行
你不需要扫描表两次就可以得到你想要的结果;你可以用窗口函数来解决这个最大的n个一组的问题
查询:

select plan_id, training_organization
from (
    select 
        t.*, 
        row_number() over(partition by plan_id order by plan_last_changed_date desc) rn
    from idp.trainee_search_vw t
) t
where rn = 1

您还可以使用聚合和oracle的 keep 语法:

select 
    plan_id, 
    max(training_organization) 
        keep(dense_rank first order by plan_last_changed_date desc) training_organization
from idp.trainee_search_vw
group by plan_id
1tu0hz3e

1tu0hz3e4#

with latestplans as 
  (    select plan_id, max(plan_last_changed_date) max-plan_date
       from idp.trainee_search_vw 
       group by plan_id
   )

 select vw.plan_id, vw.training_organization,lp.max_plan_date
  from idp.trainee_search_vw vw
   Inner join  latestplans lp on lp.plan_id=vw.plan_id

此外,还可以使用where after join

相关问题