Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - how to group hour, offset by 30 minutes

I'd like to select records in 1 hour intervals, along with the highest and loest value in the hour interval. I can do this on the hour (eg, 1:00 am, 2:00 am, 3:00 am), but I'd like to offset it by specified minutes (eg, 1:30 am, 2:30 am, 3:30 am, or 1:50am, 2:50 am, 3:50 am). I don't want to group by half-hour (eg 1:00, 1:30, 2:00, 2:30) This is the SQL I have for 1 hour intervals:

select date(date) 'aDate', hour(date) 'aHour', date, bidOpen, max(bidHigh), min(bidLow)
from data
where date > "2010-10-10"
group by aDate, aHour

I tried: hour(date) + .5 'aHour' : but it didn't work.

Thanks !!

like image 866
dld Avatar asked Dec 08 '25 03:12

dld


2 Answers

A solution is to use an helper table which contains your timeslice.

The FromHour and ToHour are just strings

TABLE timeslice
ID | FromHour | ToHour | NextDay
---+----------+--------+-------
1  | 00:30    | 01:30  | 0
2  | 01:30    | 02:30  | 0
<snip>
24 | 23:30    | 00:30  | 1

select date(date) aDate, ID ,date, bidOpen, max(bidHigh),min(bidLow)
from data inner join timeslice
    ON date >= CONCAT(date(Date),' ',FromHour) 
    and date < concat(date(DATEADD(day,NextDay,date),' ',ToHour)
group by aDate, ID
like image 89
Johan Buret Avatar answered Dec 10 '25 17:12

Johan Buret


If you store your date/times as timestamps, you can do mathy things like GROUP BY FLOOR(MOD((mytimestamp-1800)/3600)) for hour intervals starting on the half hour.

like image 23
Joshua Martell Avatar answered Dec 10 '25 16:12

Joshua Martell