# Grouping by time intervals with non-fixed ranges in MySQL

•  23-07-2023
•  |
•

Question

I'm trying to write a query that will scan through a database of connection attempts and find a group of records that exceed x attempts within 1 hour of time.

However, these one-hour ranges can't be fixed (i.e. not just 6:00-7:00, but 6:01-7:01, 6:15-7:15, etc.)

Here's an illustration

Given Max Attempts per hour = 2

```num Date
1   5:58
2   6:09
3   6:30
4   8:00
5   9:01
6   9:40
7   9:50
8   9:55
9   11:20
```

In this example, the query would return the rows 1, 2, 3, 5, 6, 7, because (1, 2, 3) and (5, 6, 7, 8) were within 1 hour of eachother and total more than 2 attempts.

Solution

``````SELECT num FROM table t1
WHERE EXISTS (
SELECT 1 FROM table t2
WHERE t2.num <> t1.num
AND TIMESTAMPDIFF(MINUTE,t1.date,t2.date) <= 60
)
``````

The query below should be faster especially if your date column is indexed

``````SELECT num FROM table t1
WHERE (MINUTE(TIMEDIFF((SELECT MAX(t2.date)
FROM table t2
WHERE t2.num <> t1.num
AND t2.date < t1.date),t1.date)) <= 60)
OR (MINUTE(TIMEDIFF((SELECT MIN(t2.date)
FROM table t2
WHERE t2.num <> t1.num
AND t2.date > t1.date),t1.date)) <= 60)
``````