Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query by time interval

Tags:

sql

sql-server

So I have used this post as a reference, however I would like to count all the rows based on a 15 minute time period.

Here is what I have so far:

SELECT      DateAdd(minute, DateDiff(minute, 0, [datetime]), 0) as Timestamp, 
            Count(*) as Tasks
FROM        [table]
GROUP BY    DateAdd(minute, DateDiff(minute, 0, [datetime]), 0)
ORDER BY    Timestamp

This is great for getting rows per minute, however I need 15 minutes... So I change:

DateAdd(minute, DateDiff(minute, 0, [datetime]), 0)

to

DateAdd(minute, DateDiff(minute, 0, [datetime]), 15)

however that is just pushing the date 15 days ahead.

Any help is appreciated!

like image 909
Hard Tacos Avatar asked Apr 24 '26 22:04

Hard Tacos


1 Answers

To get 15 minutes, divide by 15 (and then multiply again):

SELECT      DateAdd(minute, 15*(DateDiff(minute, 0, [datetime]) / 15), 0
                   ) as Timestamp, 
            Count(*) as Tasks
FROM        [table]
GROUP BY    (DateDiff(minute, 0, [datetime]) / 15)
ORDER BY    Timestamp;

SQL Server does integer division. If you want to be unambiguous about your intentions, use FLOOR().

like image 168
Gordon Linoff Avatar answered Apr 27 '26 10:04

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!