我有这个查询将日内数据聚合成日常数据(感谢Gordon Linoff)。
我每行存储1分钟的股市数据,我每天有511分钟的行(从0900到1730)。我使用MySQL vers 5.6.11
数据如下图所示
SELECT symbol, date, MAX(high) AS high, MIN(low) as low, SUM(volume) as volume,
(select open from a2a a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time limit 1) as open,
(select close from a2a a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time desc limit 1) as close
FROM a2a a1
GROUP BY symbol, date
ORDER BY symbol, date;
我的问题:
1)如果我只需要汇总数据以获得最后100个每日柱数,如何修改此查询?
2)如何将数据汇总到每周,或汇总成5分钟数据?
编辑:此版本适用于每周聚合(以及使用月份而非每周的月度聚合)
SELECT symbol, date, week(date), MAX(high) AS high, MIN(low) as low, SUM(volume) as volume,
(select open from a2a a2 where a1.symbol = a2.symbol and week(a1.date) = week(a2.date) order by time limit 1) as open,
(select close from a2a a2 where a1.symbol = a2.symbol and week(a1.date) = week(a2.date) order by time desc limit 1) as close
FROM a2a a1
WHERE date >= date_sub(CURDATE(), interval 100 week)
GROUP BY symbol, week(date)
ORDER BY symbol, date;
我仍然需要解决一些问题:
1)关于每日聚合的第一个查询返回100个日历日,而不是100个每日聚合行。我需要从最近的后退开始排序100条记录。每周聚合也是如此,我需要100个每周记录。
2)聚合5分钟或n分钟怎么样?例如,聚合从0900到0904,然后从0905到0909等聚合5分钟
答案 0 :(得分:1)
你最近100个每日酒吧是什么意思?如果你的意思是过去100天:
SELECT symbol, date, MAX(high) AS high, MIN(low) as low, SUM(volume) as volume,
(select open from a2a a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time limit 1) as open,
(select close from a2a a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time desc limit 1) as close
FROM a2a a1
WHERE date >= date_sub(CURDATE(), interval 100 day)
GROUP BY symbol, date
ORDER BY symbol, date;
如果您想要其他分组,则需要更改group by
和相关子查询以使其具有相同的表达式。例如:
SELECT symbol, week(date), MAX(high) AS high, MIN(low) as low, SUM(volume) as volume,
(select open from a2a a2 where a1.symbol = a2.symbol and a1.week(date) = a2.week(date) order by time limit 1) as open,
(select close from a2a a2 where a1.symbol = a2.symbol and a1.week(date) = a2.week(date) order by time desc limit 1) as close
FROM a2a a1
WHERE date >= date_sub(CURDATE(), interval 100 day)
GROUP BY symbol, week(date)
ORDER BY symbol, week(date);