Reputation: 20617
My table has records for every minute, now I want to fetch records with an interval of 5 minutes!
For instance
order date
1 12:01
2 12:02
....
10 12:10
11 12:11
Expected result: Order 6 and 11
Can it be done at database level?
I am using Django with MySQL
Upvotes: 0
Views: 357
Reputation: 11213
If I understand what you want,
eg every 5th record in the table? Or to put it another way each record where order is divisible by 5?
I am doing this from my head as I dont have a mysql db here to play with
SELECT * from Table where (order MOD 5) = 1;
(= 1 will give you divisible by 5 +1 so 6, 11, 16 etc)
Try that and see if you wet what your looking for.
See this page for more on MOD function
Upvotes: 0
Reputation: 13702
Did you want to group orders based on the twelve five minute intervals in an hour? By five minute intervals, I mean a minutes to interval mapping like this: (0..4 => 0, 5..9 => 1, 10..14 => 2, ...).
all_with_interval = SomeModel.objects.extra(
select={'interval': "strftime('%%M', date)/5"})
just_minutes_5_to_9 = all_with_interval.extra(
where=["interval=%d"], params=[0])
Or maybe you want a five minute range from an given start_time:
end_time = start_time + datetime.timedelta(minutes=5)
start_plus_5_inclusive = SomeModel.filter(date__range=(start_time, end_time)
start_plus_5_exclusive = start_plus_5_inclusive.exclude(end_time)
The exclude() is there because the range filter is inclusive and you probably want to exclude the end_time for this current question. If you do not exclude end_time you could get records in a 5 minute + ~1 second time range.
Upvotes: 0
Reputation: 798626
SomeModel.objects.extra(select={'fiveminutes': 'MINUTE(date)%5=0'},
where='fiveminutes=1')
Upvotes: 3