Search code examples
mysqldatetimetimesample

MySQL sampling data by datetime field


I have a MySQL table structured like this:

ID     | data           | Timestamp          | secondary_key |         
--------------------------------------------------------------
|1     | blahblah       |2018-09-03 10:45:27 | value1        |
--------------------------------------------------------------
|2     | someotherblah  |2018-09-08 10:46:56 | value2        |
--------------------------------------------------------------
|3     | blahblahagain  |2018-09-03 10:17:02 | value1        |
--------------------------------------------------------------
|4     | someotherblah  |2018-09-03 10:52:02 | value1        |
--------------------------------------------------------------

and I need to select records with a given value of secondary_key by sampling them in the past every 30 minutes on Timestamp field (i.e. from the data above: if now is 10:53 and secondary key = value1, I want my query to return only records with ID = 4 and 3). How can I achieve that?

I hope my question can be understood, sorry for my poor english.

EDIT: Here is the expected output if the query was performed on 2018-09-03 10:53

|ID    | data           | Timestamp          | secondary_key |         
--------------------------------------------------------------
|4     | someotherblah  |2018-09-03 10:52:02 | value1        |
--------------------------------------------------------------
|3     | blahblahagain  |2018-09-03 10:17:02 | value1        |
--------------------------------------------------------------

Solution

  • you could use a join on a subselect group by 30 minutes

    select * from my_table 
    inner join ( 
      SELECT  min(Timestamp) min_time, secondary_key
      from my_table 
      where secondary_key = 'value1'
      GROUP BY ROUND(UNIX_TIMESTAMP(timestamp)/(30* 60)), secondary_key
      ) t on  my_table.Timestamp = t.min_time and t.secondary_key = my_table.secondary_key;