Skip to content
Advertisement

MySQL to select max value between on and off time stamps plus 3 seconds

There’s a transporter inlet valve sensor which data is collected to a MySQL DB table showing the intake valve open and close cycles with the time stamps. There’s also a live weight sensor which data is collected to a MySQL DB table from the correlated transporter showing the live weight value as it changes with a time stamp.

I’ve built the below simplified sample query against a small sample of this table data to show the data I need to further manipulate with another subquery, etc. to put the data in a temp table.

MySQL Query to Temp Table


Struggling With…

I’m struggling to easily figure out a way to show the records where I see only the maximum weight between each on and off cycle but add in 3 seconds after the off cycle’s time stamp to find the maximum weight for the cycle.

Clarifying SQL maybe…


What I want…

Basically I want to omit the Null statuses but show the maximum weight value between each On and Off cycle (+3 seconds after Off timestamp) with the maximum weight in the Weight column of the Off status records but leave On records Null for the Weight column.

Example Desired Result

enter image description here


Here’s a small sample of the MySQL data for you to query and play with….

Note: Create the below table and insert the data, this is what can be used to try to get the desired results I’m asking about.

Advertisement

Answer

The query below selects all rows where the status isn’t null.

For the rows where the status is ‘Off’ it uses a subquery to return the maximum weight between the most recent ‘On’ and the current ‘Off’ + 3 seconds

http://sqlfiddle.com/#!9/f27fb/6

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement