2010-08-30 60 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