gpt4 book ai didi

sql - Oracle嵌套相关子查询问题

转载 作者:行者123 更新时间:2023-12-04 18:14:59 24 4
gpt4 key购买 nike

考虑具有一对多关系的表1和表2(表1是主表,表2是明细表)。我想从table1获取记录,其中一些值('XXX')是与table1相关的详细记录的table2中最近记录的值。我想做的是这样的:

select t1.pk_id
from table1 t1
where 'XXX' = (select a_col
from ( select a_col
from table2 t2
where t2.fk_id = t1.pk_id
order by t2.date_col desc)
where rownum = 1)

但是,由于在相关子查询中对table1(t1)的引用是两层深的,因此会弹出一个Oracle错误(无效的id t1)。我需要能够重写它,但是一个警告是只能更改where子句(即,初始select和from必须保持不变)。能做到吗

最佳答案

这是另一种分析方法:

select t1.pk_id
from table1 t1
where 'XXX' = (select distinct first_value(t2.a_col)
over (order by t2.date_col desc)
from table2 t2
where t2.fk_id = t1.pk_id)

这是使用排名函数的相同想法:
select t1.pk_id
from table1 t1
where 'XXX' = (select max(t2.a_col) keep
(dense_rank first order by t2.date_col desc)
from table2 t2
where t2.fk_id = t1.pk_id)

关于sql - Oracle嵌套相关子查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5314321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com