Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning rows of aggregate results from single SQL query

Tags:

sql

time

mysql

I have a MySQL table containing a column to store time and another to store a value associated with that time.

time | value
------------
 1   |  0.5     
 3   |  1.0     
 4   |  1.5 
.... | .....

The events are not periodic, i.e., the time values do not increment by fix interval.

As there are large number of rows (> 100000), for the purpose of showing the values in a graph I would like to be able to aggregate (mean) the values for an interval of fixed size over the entire length of time for which the data is available. So basically the output should consist of pairs of interval and mean values.

Currently, I am splitting the total time interval into fixed chunks of time, executing individual aggregate queries for that interval and collecting the results in application code (Java). Is there a way to do all of these steps in SQL. Also, I am currently using MySQL but am open to other databases that might support an efficient solution.

like image 282
Punit Avatar asked Dec 05 '25 01:12

Punit


1 Answers

SELECT FLOOR(time / x) AS Inter, AVG(value) AS Mean
FROM `table` 
GROUP BY Inter;

Where x is your interval of fixed size.

like image 156
JK. Avatar answered Dec 07 '25 15:12

JK.