我有一个MySQL数据库,每15分钟记录一次数据.为简单起见,我们假设有两个字段:
DATETIME Created
Double Value
我想绘制一个图表,每小时需要一小时的开盘价,最小值,最大值和收盘价.为此,我需要将MySQL查询的结果返回给我的PHP来创建一个JSON.我想在MySQL查询中执行此操作,以便缓存响应.
这是一个问题的例子,给出了9个数据点试图获得2小时组:
Creation Value
2014-03-25 12:15:00 413.17011
2014-03-25 12:00:00 414
2014-03-25 11:45:00 415
2014-03-25 11:30:00 415
2014-03-25 11:15:00 415.5
2014-03-25 11:00:00 415.5
2014-03-25 10:45:00 416
2014-03-25 10:30:00 416
2014-03-25 10:15:00 415.99
我会需要:
Hour 1 (11:15:00 to 12:15:00)
Open: 415.5
Close: 413.17011
High: 415.5
Low: 413.17011
Hour 2 (10:15:00 to 11:15:00)
Open: 415.99
Close: 415.5
High: 416
Low: 415.5
当然,整整24小时都需要重复,这只是一个例子.
任何帮助真的很感激!
以下是该示例的当前MysqL转储(使用MysqL版本2.6.4-pl3):
--
-- Table structure for table `exampleTable`
--
CREATE TABLE `exampleTable` (
`created` datetime NOT NULL,
`value` double NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `exampleTable`
--
INSERT INTO `exampleTable` VALUES ('2014-03-25 12:15:00', 413.17011);
INSERT INTO `exampleTable` VALUES ('2014-03-25 12:00:00', 414);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:45:00', 415);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:30:00', 415);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:15:00', 415.5);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:00:00', 415.5);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:45:00', 416);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:30:00', 416);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:15:00', 415.99);
解决方法:
让它工作
你可以试试
SELECT
DATE(created) AS day,
HOUR(created) AS hour,
(
SELECT Value FROM `table` AS b
WHERE DATE(a.created) = DATE(b.created)
AND HOUR(a.created) = HOUR(b.created)
ORDER BY created ASC LIMIT 1
) AS Open,
(
SELECT Value FROM `table` AS b
WHERE DATE(a.created) = DATE(b.created)
AND HOUR(a.created) = HOUR(b.created)
ORDER BY created DESC LIMIT 1
) AS Close,
MIN(value) AS Low,
MAX(value) AS High
FROM `table` AS a
GROUP BY DATE(created), HOUR(created)
这会按DATE HOUR对所有行进行分组,并将MIN或MAX分别计算为Low或High.要查找“打开”和“关闭”的第一行和最后一行,sql语法中最简单的是子选择.它选择与当前行相关的所有行,并按升序或降序对其进行排序.然后选择第一行.
请考虑这个组只有一小时.代替
Hour 1 (11:15:00 to 12:15:00)
Hour 2 (10:15:00 to 11:15:00)
这群人喜欢
Hour 1 (11:00:00 to 11:59:00)
Hour 2 (10:00:00 to 10:59:00)
如果要保持15分钟的偏移量,可以在上面的SQL查询中创建的所有事件中从创建的时间戳(创建 – 间隔15分钟)中减去此值.
我为你创造了a working sqlfiddle.
正如提示:如果可以,您可能希望将日期和时间分成两列(日期和时间类型).这样,您不需要每次都创建DATE(),但可以使用新的日期列.然后,您也可以为这些新列添加组合索引,从而加快查询速度.有关示例,请参见this sqlfiddle.