开发者

Find difference between SQL records that are not stored consecutively

I have a MYSQL table that stores data for solar generation at my home. There are two inverter devices that I'm polling which comprise the data in this table. To simplify, the pertinent part of my table structure (with descriptions) is something like:

id <auto_increment>
addr <int address of the inverter>
etotal <total generation since the device has been online>

I am trying to find the difference between consecutive records per inverter so that I can tell how much energy was generated in the time period between records (or between whatever period I eventually choose). If the records were inserted consistently, I could do something 开发者_高级运维like:

SELECT (t2.etotal - t1.etotal) AS eperiod 
                              FROM solars AS t1, solars AS t2 
                              WHERE t1.id+2 = t2.id AND t1.created_at >= CURDATE() 
                              AND t1.addr = 245 AND t2.addr = 245 ORDER BY t1.id;

However, this doesn't always function as desired, and it seems like a poor choice. The only other thought I've had is to select to a temporary table with auto-incrementing id, then do a similar select from that table. Interested in a single query solution if possible.


SELECT  @ptotal - etotal, @ptotal := etotal
FROM    solars
WHERE   created_at >= CURDATE() 
        AND addr = 245
ORDER BY
        created_at, id

Ignore the second column when processing the results or wrap it into a nested query (though it can be a little more slow):

SELECT  diff
FROM    (
        SELECT  @ptotal - etotal AS diff, @ptotal := etotal
        FROM    solars
        WHERE   created_at >= CURDATE() 
                AND addr = 245
        ORDER BY
                created_at, id
        ) q

Create a composite index on (addr, created_at, id) for this to work fast.

Should also support diesel generators (not tested).


Can't you just say
WHERE t1.created_at = t2.created_at?

Or I don't understand your problem :$

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜