2010-08-30 61 views
1

我有兩個表格,一個存儲當前價格,另一個存儲項目的歷史價格。我想創建一個查詢來拉取當前價格,以及當前價格和最近歷史價格之間的差額。我應該使用子查詢嗎?

在歷史表中,我有價格的開始和結束時間,所以我可以選擇最近的價格,但是如何在一個查詢中將它們全部集中起來?或者我必須做一個子查詢?

select p.current_price, 
h.historical_price 
h.historical_time 

from price p 

inner join price_history h 
on p.id = h.id 
where max(h.historical_time) 

這顯然不起作用,但這正是我想要完成的。

這給我當前和歷史價格。但我想確保我有最新的價格。我將如何做到這一點?

回答

2

我會這樣做。請注意,你可能會得到重複的記錄,如果有兩個價格條目與同一日期同一idprice_history

select p.current_price, h.historical_price, 
    p.current_price - h.historical_price as PriceDeff, h.historical_time 
from price p 
inner join (
    select id, max(historical_time) as MaxHistoricalTime 
    from price_history 
    group by id 
) hm on p.id = hm.id 
inner join price_history h on hm.id = h.id 
    and hm.MaxHistoricalTime = h.historical_time 
+0

+1正在自己寫相同的東西 – 2010-08-30 17:14:33

+0

完美地工作!非常感謝! – muncherelli 2010-08-30 17:42:26

+0

我可能會補充說,日期實際上是時間戳......所以除非價格每秒更新一次以上,否則我應該重複複製! ;) – muncherelli 2010-08-30 17:43:50

1

我不相信有沒有這樣做的方式沒有一個子查詢不壞。另一方面,如果您的表正確索引,則返回聚合函數結果的子查詢通常非常快。

+0

我沒有足夠的代表對人的回答上面發表評論,但肯定,集合函數子查詢在與容器函數相同的鍵上查詢是很重要的,否則,如果有巧合的數據與您的聚合不匹配,您可能會得到有趣的結果。 – 2010-08-30 17:21:54

0
select 
     p.current_price, 
     h3.historical_price, 
     h3.historical_time 
    from 
     price p, 
     (select h1.id, max(h1.historical_time) as MaxHT 
      from price_history h1 
      group by 1) h2, 
     price_history h3 
    where 
      p.id = h2.id 
     and p.id = h3.id 
     and h2.MaxHT = h3.historical_time