I have a MySQL table, with datetime values in each row.
I try to group by two intervals:
- Date between now and now – 1hour
- Date betwwen now – 1 hour and now – 2 hour
What i do?
SELECT MIN(date), MAX(date), count(stats.ID) as c FROM stats WHERE date BETWEEN (NOW() - INTERVAL 2 HOUR) AND NOW() GROUP BY UNIX_TIMESTAMP(date) DIV 7200
MIN(DATE) | MAX(DATE) | count |
---|---|---|
2023-03-11 18:45:15 | 2023-03-11 18:59:59 | 150 |
2023-03-11 19:00:01 | 2023-03-11 19:45:15 | 250 |
and i try this:
SELECT count(ID), MIN(date), MAX(date), sec_to_time(time_to_sec(date)- time_to_sec(DATE)%(60*60)) as intervals from stats WHERE date BETWEEN (NOW() - INTERVAL 2 HOUR) AND NOW()group by intervals
MIN(DATE) | MAX(DATE) | count |
---|---|---|
2023-03-11 18:45:15 | 2023-03-11 18:59:59 | 150 |
2023-03-11 19:00:00 | 2023-03-11 19:59:59 | 250 |
2023-03-11 20:00:00 | 2023-03-11 19:45:15 | 250 |
Expected result
MIN(DATE) | MAX(DATE) | count |
---|---|---|
2023-03-11 18:45:15 | 2023-03-11 19:45:15 | 150 |
2023-03-11 19:45:15 | 2023-03-11 20:45:15 | 250 |
2
Answers
Some sample data and expected output would be helpful, but can’t you just do:
or even just: