我的数据库表结构如下:
字段分别是ID,NUM1,NUM2, TIME1,TIME2, MONEY.
想要按照15分钟为间隔来统计ID的数量。效果如同下面的sql语句。
SELECT
sum(CASE when TIME1 >= '2014-02-27 8:00:00' and TIME1 < '2014-02-27 8:15:00' then 1 else 0 end) AS '1',
sum(CASE when TIME1 >= '2014-02-27 8:15:00' AND TIME1 < '2014-02-27 8:30:00' then 1 else 0 end) AS '2',
sum(CASE when TIME1 >= '2014-02-27 8:30:00' AND TIME1 < '2014-02-27 8:45:00' then 1 else 0 end) AS '3',
sum(CASE when TIME1 >= '2014-02-27 8:45:00' AND TIME1 < '2014-02-27 9:00:00' then 1 else 0 end) AS '4',
sum(CASE when TIME1 >= '2014-02-27 9:00:00' and TIME1 < '2014-02-27 9:15:00' then 1 else 0 end) AS '5'
from dealdata;
但是像上面那么写重复代码多,并且如果我改成30分钟的话,就要改动很多,所以求助sql大神,看有什么好的方法。
———————————————————————————————————分割线————————————————————————————————————
谢谢 arm 同志的帮助,现在能查询出现了
count(id)就是进站的人
但是有的时间段,根本没有进站的人,所以有的时间段没有,例如5:00 -- 5:15
如果要将没有进站的人的时间段 补全为0,该怎么做呢?
我想大声告诉你2017-05-25 15:10:22
谢邀,可以纵向排列的化,如下
SELECT count(id)
from dealdata
where timestampdiff(minute,'2014-02-27 9:15:00',`TIME1`)<0 and timestampdiff(minute,'2014-02-27 8:00:00',`TIME1`)>=0
group by floor(timestampdiff(minute,'2014-02-27 8:00:00',`TIME1`)/15)
where 限制时间段,group by里面除以你需要的时间间隔。
我不知道你为什么出错,可能和mysql版本有关,我是mysql5.6
SELECT count(*),
floor(timestampdiff(minute,'2017-1-18 16:00:00',`time`)/30),
date_add('2017-1-18 16:00:00',interval 30*floor(timestampdiff(minute,'2017-1-18 16:00:00',`time`)/30) MINUTE)
FROM 我是马赛克.我是马赛克
group by floor(timestampdiff(minute,'2017-1-18 16:00:00',`time`)/30)
结果
看了下,跑的还是蛮快的,0.3s不到