MYSQL查询:如何获取每个类别的值?

MYSQL查询:如何获取每个类别的值?,mysql,sql,Mysql,Sql,我有一个巨大的表,上面有数百万条记录,它们按时间戳存储股票价值。结构如下: Stock, timestamp, value goog,1112345,200.4 goog,112346,220.4 Apple,112343,505 Apple,112346,550 我想按时间戳查询这个表。如果时间戳匹配,则应返回所有相应的股票记录,如果没有该时间戳的股票记录,则应返回前一个股票记录。在上面的例子中,如果我按timestamp=1112345查询,那么查询应该返回2条记录: goog

我有一个巨大的表,上面有数百万条记录,它们按时间戳存储股票价值。结构如下:

Stock, timestamp, value

goog,1112345,200.4

goog,112346,220.4

Apple,112343,505

Apple,112346,550
我想按时间戳查询这个表。如果时间戳匹配,则应返回所有相应的股票记录,如果没有该时间戳的股票记录,则应返回前一个股票记录。在上面的例子中,如果我按timestamp=1112345查询,那么查询应该返回2条记录:

  goog,1112345,200.4

  Apple,112343,505 (immediate previous record)

我尝试了几种不同的方法来编写这个查询,但没有成功&我确信我遗漏了一些东西。有人能帮忙吗。

从这个TBL中选择股票、时间戳、价值,其中时间戳=?然后把时间戳填到应该是什么?您的演示查询是可用的

我认为没有一种简单的方法来执行此查询。以下是一种方法:

select tprev.*
from (select t.stock,
             (select timestamp from t.stock = s.stock and timestamp <= <whatever> order by timestamp limit 1
             ) as prevtimestamp
      from (select distinct stock
            from t
           ) s
    ) s join
    t tprev
    on s.prevtimestamp = tprev.prevtimestamp and s.stock = t.stock

RDBMS中的行没有固有的顺序。那么在什么意义上一行紧接着另一行呢?如果你尝试了什么,你应该在你的问题中添加代码来显示你尝试了什么。可能只是一个简单的tweeking它需要。。!无法保证这将返还所有库存。
select tprev.*
from (select t.stock,
             (select timestamp from t.stock = s.stock and timestamp <= <whatever> order by timestamp limit 1
             ) as prevtimestamp
      from (select distinct stock
            from t
           ) s
    ) s join
    t tprev
    on s.prevtimestamp = tprev.prevtimestamp and s.stock = t.stock
select tprev.*
from (select t.stock,
             max(timestamp) as prevtimestamp
      from t
      where timestamp <= YOURTIMESTAMP
      group by t.stock
    ) s join
    t tprev
    on s.prevtimestamp = tprev.prevtimestamp and s.stock = t.stock