Fix bad data in energy tab

Hi! I built a query (mysql - mariadb based) usefull to fix all data set from first row.

My first row was at 11.00 so start from a posive value, you have to customize this dataset to adapt to your situation:


@original_total := 11.25, // starting value, first row, you can set what you want here
@first_state := 11.25, // use same value of previous row or a higher value
@prev_state := 0,
@first_id := 1492, // id of your first row, with sum and state equal to 11.25 in this example
@meta_id := 116, // metadata id

you can adapt it for statistics and short_term, just change table name and fix variables! :smiley:
Hope it will be usefull!

UPDATE
    statistics AS s
INNER JOIN(
    SELECT
        myid,
        cumulative_sum AS mysum
    FROM
        (
        SELECT
            t.id AS myid,
            t.start,
            t.state,
            t.sum,
            IF(
                t.id = @first_id,
                @running_total := @original_total,
                IF(
                    (t.state - @prev_state) < 0,
                    @running_total := @running_total + t.state,
                    @running_total := @running_total +(t.state - @prev_state)
                )
            ) AS cumulative_sum,
            @diff :=(t.state - @prev_state) AS diff_state,
            @prev_state :=(t.state) AS prev_state,
            IF(
                t.id = @first_id,
                @risultato := @first_state,
                @risultato :=(t.state - @diff)
            ) AS risultato
        FROM
            (
        SELECT
            *
        FROM
            statistics
        ) t
    JOIN(
        SELECT
            @original_total := 11.25,
            @first_state := 11.25,
            @prev_state := 0,
            @first_id := 1492,
            @meta_id := 116,
            @diff := 0
    ) r
WHERE
    metadata_id = @meta_id AND id >= @first_id
ORDER BY
    t.id
    ) d
) m
ON
    s.id = m.myid
SET
    s.sum = m.mysum
WHERE
    metadata_id = 116;