Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first value of every minute in table

Tags:

sql

mysql

I've been trying to work this one out for a while now, maybe my problem is coming up with the correct search query. I'm not sure.

Anyway, the problem I'm having is that I have a table of data that has a new row added every second (imagine the structure {id, timestamp(datetime), value}). I would like to do a single query for MySQL to go through the table and output only the first value of each minute.

I thought about doing this with multiple queries with LIMIT and datetime >= (beginning of minute) but with the volume of data I'm collecting that is a lot of queries so it would be nicer to produce the data in a single query.

Sample data:

id  datetime             value
1   2015-01-01 00:00:00  128
2   2015-01-01 00:00:01  127
3   2015-01-01 00:00:04  129
4   2015-01-01 00:00:05  127
...
67  2015-01-01 00:00:59  112
68  2015-01-01 00:01:12  108
69  2015-01-01 00:01:13  109

Where I would want the result to select the rows:

1   2015-01-01 00:00:00  128
68  2015-01-01 00:01:12  108

Any ideas?

Thanks!

EDIT: Forgot to add, the data, whilst every second, is not reliably on the first second of every minute - it may be :30 or :01 rather than :00 seconds past the minute

EDIT 2: A nice-to-have (definitely not required for answer) would be a query that is flexible to also take an arbitrary number of minutes (rather than one row each minute)

like image 740
CallumA Avatar asked Dec 30 '25 02:12

CallumA


1 Answers

SELECT t2.* FROM
( SELECT MIN(`datetime`) AS dt
  FROM tbl
 GROUP BY DATE_FORMAT(`datetime`,'%Y-%m-%d %H:%i')
) t1
JOIN tbl t2 ON t1.dt = t2.`datetime`

SQLFiddle

Or

SELECT * 
FROM tbl 
WHERE dt IN ( SELECT MIN(dt) AS dt
              FROM tbl
              GROUP BY DATE_FORMAT(dt,'%Y-%m-%d %H:%i'))

SQLFiddle

SELECT t1.* 
FROM tbl t1
LEFT JOIN (
  SELECT MIN(dt) AS dt 
  FROM tbl
  GROUP BY DATE_FORMAT(dt,'%Y-%m-%d %H:%i')
) t2 ON t1.dt = t2.dt
WHERE t2.dt IS NOT NULL

SQLFiddle

like image 66
potashin Avatar answered Jan 01 '26 16:01

potashin



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!