检索历史数据

时间:2014-02-16 12:28:21

标签: mysql

我有一个包含记录的数据库,我需要制作过去10天的市场价格历史,并且我会返回开盘价和收盘价。

数据库是:

ID | MARKET | EXCHANGE | LAST_TRADE | TIMESTAMP
1  |   1    |    1     |     25     | 1392562800 #2014/2/16 @ 15:0:0 <-- "Today's Open" (first insert of the day)
2  |   1    |    1     |     35     | 1392573600 #2014/2/16 @ 18:0:0
3  |   1    |    1     |     45     | 1392584400 #2014/2/16 @ 21:0:0
4  |   1    |    1     |     55     | 1392562800 #2014/2/16 @ 23:59:0 <-- "Today's Close" (last insert of the day)

假设我们有更多的日子,我们必须按天分组并返回当天市场和交易所= 1的开盘价和收盘价

示例:

ID | MARKET | EXCHANGE |    DATE   | OPEN | CLOSE
 1 |   1    |    1     | 2014/2/16 |  25  |  55

1 个答案:

答案 0 :(得分:2)

converting the timestamp之后并按日期分组,您可以使用this trick获取聚合中的第一行和最后一行:

select 
  market, 
  exchange, 
  date(FROM_UNIXTIME(timestamp)),
  SUBSTRING_INDEX( GROUP_CONCAT(CAST(lastTrade AS CHAR) ORDER BY timestamp), 
         ',', 1 ) as open,
  SUBSTRING_INDEX( GROUP_CONCAT(CAST(lastTrade AS CHAR) ORDER BY timestamp DESC), 
         ',', 1 ) as close
from historicdata 
group by market, exchange, date(FROM_UNIXTIME(timestamp));

Fiddle here

您的时间戳评论看起来与实际时间戳不完全匹配 - 第1行和第4行都有时间戳1392562800。小提琴还包括盘中高点收盘价,就像测试案例一样:)