在oracle中进行子选择

时间:2011-04-21 07:16:07

标签: sql oracle

我正在尝试从子选择中的另一个表中选择最新价格。但我无法弄清楚如何让它发挥作用。

这是我尝试过的:

select something, somthingelse, 
  (
    select * from 
    (
      select QUOTE_PRICE as old_price
      from price_history
      where price_history.part_no= article_table.part_no
      order by valid_from desc
    ) where rownum=1
  )
from  article_table where rownum < 5

子选择本身有效,但找不到article_table.part_no

  

SQL错误:ORA-00904:“article_table”。“part_no”:标识符无效

更新

目前的解决方案:

select something, somethingelse, (
  SELECT MIN(QUOTE_PRICE) KEEP (DENSE_RANK FIRST ORDER BY valid_from)
  FROM price_history
  WHERE part_no=article_table.part_no
) as old_price
from  article_table a where rownum < 5

3 个答案:

答案 0 :(得分:6)

在Oracle中,子查询只能查看父级查询中一个级别的值。由于您有两个嵌套选择,因此内部选择无法看到外部选择的值。

您可以先执行加入:

SELECT something, somthingelse, old_price
  FROM (SELECT a.something, a.somthingelse, p.quote_price old_price,
               row_number() over (PARTITION BY a.part_no 
                                  ORDER BY valid_from DESC) rnk
           FROM article_table a
           LEFT JOIN price_history p ON a.part_no = p.part_no)
 WHERE rnk = 1;

您还可以使用PL / SQL函数,该函数在给定quote_price时将从price_history返回第一个article_table.part_no

答案 1 :(得分:2)

在最外层的查询中尝试别名article_table

select a.something, a.somthingelse, 
  (
    select * from 
    (
      select QUOTE_PRICE as old_price
      from price_history
      where price_history.part_no= a.part_no
      order by valid_from desc
    ) where rownum=1
  )
from  article_table a where rownum < 5

此外,您可能希望查看Oracle分析函数,以便为此类目的进行更简单的查询:

http://psoug.org/reference/analytic_functions.html

答案 2 :(得分:1)

我会尝试以下方法:

select something, somethingelse, last_value(quote_price) over (partition by part_no order by valid_from asc)
  from article_table inner join price_history using (part_no)
 where rownum < 5;