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

时间:2013-01-17 23:32:51

标签: mysql sql

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

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)

我尝试了几种不同的方法来编写此查询但没有成功&我确定我错过了什么。有人可以帮忙吗。

3 个答案:

答案 0 :(得分:1)

SELECT `Stock`, `timestamp`, `value`
FROM `myTable`
WHERE `timestamp` = 1112345
  UNION ALL
SELECT `Stock`, `timestamp`, `value`
FROM `myTable`
WHERE `timestamp` < 1112345
ORDER BY `timestamp` DESC
LIMIT 1

答案 1 :(得分:0)

select Stock, timestamp, value from thisTbl where timestamp = ?并填写时间戳到应有的位置?您的演示查询可用on this fiddle

答案 2 :(得分:0)

我认为没有一种简单的方法可以进行此查询。这是一种方法:

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

这是获取记录的先前或相等的时间戳,然后重新加入。如果您有(股票,时间戳)索引,那么这可能会相当快。

它的另一个措辞使用group by

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