I have a simple table like this (in real x-thousand values):
On this table I'm doing a query to get the differences (which works fine):
select
EL.sensor_id,
EL.value_id,
EL.time,
EL.value,
if( @lastSN = EL.sensor_id, EL.value - @lastValue, 0000.00 ) as diff,
@lastSN := EL.sensor_id,
@lastValue := EL.value
from
data_test_debug EL,
( select @lastSN := 0,
@lastValue := 0 ) SQLVars
where EL.value_id = "gas"
order by
EL.sensor_id,
EL.time
The result looks like this:
Now I have a problem because I have to group the diff data.
by day or month or week or year (for representing the data in charts)
I tried something like this:
select MONTHNAME(EL.time), SUM(EL.diff)
FROM data_test_debug EL,
(select
EL.sensor_id,
EL.value_id,
EL.time,
EL.value,
if( @lastSN = EL.sensor_id, EL.value - @lastValue, 0000.00 ) as diff,
@lastSN := EL.sensor_id,
@lastValue := EL.value
from
data_test_debug EL,
( select @lastSN := 0,
@lastValue := 0 ) SQLVars
where EL.value_id = "gas"
order by
EL.sensor_id,
EL.time) AS t
GROUP BY YEAR(EL.time), MONTH(EL.time)
but had no look to get results..
The data is hourly collected therefore grouping is needed.
Don't join the table again. Apply the grouping directly to the subquery:
SELECT YEAR(time), MONTHNAME(time), SUM(diff)
FROM (select EL.sensor_id,
EL.value_id,
EL.time,
EL.value,
if(@lastSN = EL.sensor_id, EL.value - @lastValue, 0.0) as diff,
@lastSN := EL.sensor_id,
@lastValue := EL.value
FROM data_test_debug EL, (SELECT @lastSN := 0,
@lastValue := 0) SQLVars
WHERE EL.value_id = "gas"
ORDER BY EL.sensor_id, EL.time
) AS t
GROUP BY YEAR(time), MONTH(time)
It can be greatly simplified by removing all those fields that you're not using, but you can do that after you get it working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.