mysqlsqldatetimeoperation

Subtract to numbers in relation to time/date specific query in Mysql // Nodered


hy, beeing a noob in mysql i am trying to substract two numbers in relation to a time/date specific query:

Trying to display the actual daily power consumption of my house i can extract the total input value in KWH via MODBUS using Node red from my Smart Meter. But i have to process them to see the daily consumption.

enter image description here

The result of the query should be:

value inputpwr of the latest entry of the actual day - inputpwr of last entry yesterday.

So when i do this query i will get the actual daily power demand. I was able to get the latest value, but i am failing to substract them by identifying yesterdays last entry.

SELECT inputpwr FROM pwrtable ORDER BY date DESC,time DESC LIMIT 1

Can anyone help please, im not the SQL guy.


Solution

  • row_number() to add row id to every records by order desc, then the latest record will be the rn = 1

    Lag() to get the previous record based on the order by date and time.

     with cte as (
      select s.*
      from (
         SELECT *, row_number() over(partition by _date order by _date desc, _time desc) as rn
         FROM pwrtable
      ) as s
      where rn = 1
      order by _date desc
    )
    select _date, inputpwr - lag(inputpwr) over (order by _date, _time) as consumption
    from cte
    

    Demo here