如何选择行的第一个和最后一个值以及间隔5分钟

时间:2016-01-20 17:04:40

标签: mysql sql

我有一张带有样品外汇的桌子,一分钟的酒吧报价。

id,quote_name,quote_date,quote_time,open_rate,close_rate,high_rate,low_rate
"1417","EURUSD","2015-01-01","13:01:00","1.2096","1.2096","1.2097","1.2096"
"1418","EURUSD","2015-01-01","13:02:00","1.2097","1.2096","1.2097","1.2096"
"1419","EURUSD","2015-01-01","13:04:00","1.2096","1.2098","1.2101","1.2096"
"1420","EURUSD","2015-01-01","13:05:00","1.2099","1.2099","1.2099","1.2099"

是否可以创建将返回5分钟间隔引号的select语句。我的意思是它应该在每5分钟间隔之间选择5行并从第一行返回open_rate,从最后一个引用返回close_rate,以及从high_rate和low_rate返回min和max。 有可能吗?怎么做。

我所知道的是如何在两个日期之间选择最小值和最大值。

1 个答案:

答案 0 :(得分:1)

获得五分钟的间隔有点痛苦。一种方法是转换为秒并除以300.然后,获得第一个和最后一个也很棘手。在这种情况下,我会建议使用substring_index()group_concat()

select quote_date, min(open_time) as open_time,
       substring_index(group_concat(open_rate order by quote_time), ',', 1) as first_open,
       substring_index(group_concat(close_rate order by quote_time desc), ',', 1) as last_close,
       min(high_rate), max(high_rate),
       min(low_rate), max(low_rate)
from quotes
group by quote_date, floor(to_seconds(quote_time) / 300);