I have a table that records values from electrical meters
The table looks like this
SELECT created_at, value, delta
FROM metervalues
ORDER BY created_at
2013-05-28 07:59:00 | 752105,6 | null
2013-05-28 08:14:00 | 752156,0 | null
2013-05-28 08:29:00 | 752207,2 | null
2013-05-28 08:44:00 | 752259,2 | null
2013-05-28 08:59:00 | 752312,8 | null
2013-05-28 09:14:00 | 752366,4 | null
2013-05-28 09:29:00 | 752417,2 | null
now I want to calculate the consumption so
delta(current record) = value(current record) - value(previous record)
It could happen that records are added later so the record id's don't necessarily follow the "created_at" order.
Currently I'm loading the data using a ruby script then loop and update the records. This is very slow.
Can this be solved by SQL direct ? I tried some samples with cursors but did not really find a solution.