Question

I am making line graph from huge number of data from MySQL database. I can't pull out all of the data because allowed memory size in PHP would get exhausted so I need to re-sample the data.

I can't select (for example) every 3rd row from the database because each data point represents relative value (=change in user balance like +5 instead of actual state of user balance which could be 1000) so what I would need is SUM from group of n rows.

example of data in database
-10
-10
-10
 20
 20
-20
-10
-10
 20

expected output for SUM grouping by 3 rows
-30
 20
  0
Was it helpful?

Solution

The fastest way to do this is with variables.

select sum(data)
from (select t.*, (@rn := @rn + 1) as rn
      from table t cross join
           (select @rn := -1) const
     ) t
group by rn div 3;

You should really have a column that specifies the ordering of the rows, so the subquery would have an order by <ordering column> to ensure consistent results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top