我有一个MySQL 5.7表,每行都有时间戳。我的目标是计算some_id列的值并根据指定的30分钟间隔对其进行分组。并仅显示计数大于0的间隔。 输入:
timestamp some_id
-------------- ------
2019-01-19 05:30:12 4
2019-01-19 05:40:12 8
2019-01-19 15:37:40 2
2019-01-20 01:57:38 2
2019-01-20 07:10:07 4
2019-01-20 22:10:38 2
2019-01-21 08:35:55 4
预期:
interval COUNT(some_id)
------------- -----------
05:30:00 - 06:00:00 2
07:00:00 - 07:30:00 1
08:30:00 - 09:00:00 1
22:00:00 - 22:30:00 1
etc..........
我尝试实施此处介绍的解决方案MySQL Group by specific 24 hour interval-但没有成功。
我的尝试
我不确定这是否是正确的解决方案
SELECT CONCAT(
DATE_FORMAT(table.timestamp, "%H:"),
IF("30">MINUTE(table.timestamp),
(CONCAT("00-",DATE_FORMAT(DATE_ADD(table.timestamp, INTERVAL 60 MINUTE), "%H:"),"30")),
(CONCAT("30-",DATE_FORMAT(DATE_ADD(table.timestamp, INTERVAL 30 MINUTE), "%H:"),"00")))) AS time_period,
COUNT(*)
FROM table
GROUP BY time_period;
答案 0 :(得分:2)
您提供的链接具有非常深奥的解决方案。试试:
SELECT CONCAT(
DATE_FORMAT(mydate, "%Y-%m-%d %H:"),
IF("30">MINUTE(mydate), "00", "30")
) AS time_bin,
COUNT(*)
FROM mytable
GROUP BY CONCAT(
DATE_FORMAT(mydate, "%Y-%m-%d %H:"),
IF("30">MINUTE(mydate), "00", "30")
)
答案 1 :(得分:1)
最快,最简单的解决方案是这样:
CREATE TABLE IF NOT EXISTS `events` (
`id` int unsigned NOT NULL,
`timestamp` DATETIME NOT NULL,
PRIMARY KEY (`timestamp`)
);
INSERT INTO `events` (`timestamp`, `id`) VALUES
('2019-01-19 05:30:12', 4),
('2019-01-19 06:20:12', 4),
('2019-01-19 15:37:40', 2),
('2019-01-20 01:57:38', 2),
('2019-01-20 07:10:07', 4),
('2019-01-20 22:10:38', 2),
('2019-01-21 08:35:55', 4);
查询:
SELECT
DATE(timestamp), HOUR(timestamp), SUM(id)
FROM
events
GROUP BY 1,2 ORDER BY 1,2;
产生了
http://sqlfiddle.com/#!9/fadd28/5
编辑:糟糕,错过了30分钟的间隔要求。但是我想你明白了。您可以在上面的链接中使用我的解决方案。:)
但是,如果您的数据库支持WINDOW函数,那就更好了。
此外,出于这个目的,我个人创建了一个聚合表,该表将包含每小时的计数器,并在插入期间使用TRIGGER进行更新。
答案 2 :(得分:0)
我听了@symcbean所说的话,但略微调整了一下,以便给出您想要的东西:
SELECT CONCAT(
DATE_FORMAT(timestamp, "%H:00 - "),
IF("00">MINUTE(timestamp), CONCAT(HOUR(timestamp), ":00"), CONCAT(HOUR(timestamp), ":30"))
) AS Time,
COUNT(*)
FROM mysql_24h_cycle
GROUP BY CONCAT(
DATE_FORMAT(timestamp, "%H:"),
IF("30">MINUTE(timestamp), CONCAT(HOUR(timestamp), ":00"), CONCAT(HOUR(timestamp), ":30"))
)