从我之前的问题开始,我有这个查询来执行从日内数据到日常数据的数据聚合
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;
但由于它使用日历日,因此返回的每日聚合行数少于100个。
1)如何修改此查询以获取100条最新记录?
2)如何聚合到5分钟而不是每天(即第一行聚合数据从0900到0904,然后从0905到0909等)?
我使用mySQL 5.6.11,存储的数据如下
我每行存储1分钟的股票市场数据,我每天有511分钟的行(从0900到1730)。
答案 0 :(得分:0)
粗糙且未经测试的例子。
SELECT symbol, Sub1.aDay, 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
(
SELECT DATE_SUB(CURDATE(), INTERVAL (Tens.a * 10 + Units.a) DAY) AS aDay
FROM (SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units,
(SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens
) Sub1
LEFT JOIN A2A a1
ON Sub1.aDay = a1.date
GROUP BY symbol, Sub1.aDay
ORDER BY symbol, Sub1.aDay;
这是一个子查询,它生成数字0到99,并从当前日期减去天数。给你100天的范围。然后根据日期将主表加入该列表。