Mysql – Query calculating AVG per minute GROUP BY timestamp

MySQL

I'm trying to query the average for each minute, so I can generate graph per 5, 15, 30 minutes.

Here is my table, date stored in MySQL DateTime data type field.

timestamp            vif_2_rx    
-------------------  ------------
2015-04-16 10:10:00  3.250400    
2015-04-16 10:14:40  593.508800  
2015-04-16 10:14:40  593.508800  
2015-04-16 10:24:40  153.693100   
2015-04-16 10:24:40  153.693100  
2015-04-16 10:29:55  54.976200   
2015-04-16 10:34:40  124.285100  
2015-04-16 10:34:40  124.285100  
2015-04-16 10:34:40  124.285100  
2015-04-16 10:39:55  49.292200   
2015-04-16 10:44:45  56.090700   
2015-04-16 10:44:45  56.090700   
2015-04-16 10:44:45  56.090700   
2015-04-16 10:49:55  20.641100   
2015-04-16 10:54:45  21.694600   
2015-04-16 10:54:45  21.694600   

This is what I have tried so far.

SELECT TIMESTAMP, vif_2_rx FROM md_metrics_status WHERE vm_name = 'r-23-VM' 
AND TIMESTAMP > NOW() - INTERVAL 15 MINUTE 
GROUP BY MINUTE(TIMESTAMP);

Results:

TIMESTAMP            vif_2_rx    
-------------------  ------------
2015-04-16 10:04:40  94.752800   
2015-04-16 10:10:00  3.250400    
2015-04-16 10:14:40  593.508800  
2015-04-16 11:20:00  14.756200   
2015-04-16 10:24:40  153.693100  
2015-04-16 10:29:55  54.976200   
2015-04-16 13:30:00  76.920200   
2015-04-16 10:34:40  124.285100  
2015-04-16 10:39:55  49.292200   
2015-04-16 10:44:45  56.090700   
2015-04-16 10:49:55  20.641100   
2015-04-16 09:54:45  43.382700   
2015-04-16 11:59:55  78.070000 

I'm guessing this would only pick a value from that minute without calculating the average of it, how can I go about calculating the average of each minute.

Any ideas on how I can go about doing that?

Thank you

Best Answer

  1. You should use AVG function if you need to get the average
  2. Using MINUTE function will return the minute part from the date. i.e. 10:05:03 and 11:05:33 will give the same result. (It is fine if the interval is less than 60 minutes, however, it is safer to use the following query:)

SELECT left(timestamp, 16) as mtimestamp, avg(vif_2_rx) FROM md_metrics_status WHERE vm_name = 'r-23-VM' AND TIMESTAMP > NOW() - INTERVAL 15 MINUTE GROUP BY mtimestamp