2011-04-21 65 views
3

我試圖從子選擇中的另一個表中選擇最新的價格。但我無法弄清楚如何讓它工作。在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 Error: ORA-00904: "article_table "."part_no": invalid identifier

更新:

當前的解決方案:

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 

回答

5

在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函數給出一個article_table.part_no時會從price_history返回第一quote_price

+0

不會工作。我不想只選擇一行。我想獲得article_table中所有行的前一個價格。或者,也許我誤解了你的建議? – jgauffin 2011-04-21 08:21:17

+0

@jgauffin:運行查詢:) - 查詢將每個'article_table'行返回一行。 – 2011-04-21 08:21:51

+0

是的。謝謝。 +1。您如何看待我添加到我的問題中的解決方案? – jgauffin 2011-04-21 08:29:43

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

+0

走樣沒有幫助:( – jgauffin 2011-04-21 07:25:40

+0

我問你的答案的反刪除,因爲鏈接分析功能幫助MED在我更新的答案的解決方案,我如果我沒有一個更清潔的解決方案,我會接受它。不要那麼快地刪除答案。 – jgauffin 2011-04-21 17:47:39

+0

如你所願... :-)我認爲主要答案是錯誤的,分析函數也是由其他人提出的,所以我的答案是誤導其他讀者... – 2011-04-21 22:51:56

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;