I am trying to fetch some averages and some sums over several rows, grouping by each hour of the day. Plus I want to fetch an additional column, where I don't get the sums for each hour (which is fetched when grouping), but where I want to fetch the total sum over all rows until that specific date. The SQL-statement is posted below.
My problem is now, that executing the query on a MySQL database over ~25k rows takes about 8 seconds (CPU i5/8GB RAM). I identified that the subselect (... AS 'rain_sum'
) makes it very slow. My question is now: Do I think in a too complex way? Is there an easier way to get the same results I get from the query below?
SELECT
`timestamp_local` AS `date`,
AVG(`one`) AS `one_avg`,
AVG(`two`) AS `two_avg`,
SUM(`three`) AS `three_sum`,
(SELECT SUM(`b`.`three`)
FROM `table` AS `b`
WHERE `b`.`timestamp_local` <= SUBDATE(`a`.`timestamp_local`, INTERVAL -1 SECOND)
LIMIT 0,1) AS `three_sum`
FROM `table` AS `a`
GROUP BY
HOUR( `a`.`timestamp_local` ),
DAY( `a`.`timestamp_local` ),
MONTH( `a`.`timestamp_local` ),
WEEK( `a`.`timestamp_local` ),
YEAR( `a`.`timestamp_local` )
ORDER BY `a`.`timestamp_local` DESC
LIMIT 0, 24;