energyanalysis/function_total_energy_by_day_and_device.sql

38 lines
1.2 KiB
PL/PgSQL

create or replace function total_energy_by_day_and_device(p_day date, p_device varchar)
returns double precision
language plpgsql
as $$
declare
v_firstEnergy double precision;
v_lastEnergy double precision;
v_total double precision;
begin
select energy
into v_lastEnergy
from power_measurement_t
where time = (
select max(time)
from power_measurement_t
where time between p_day + time '00:00' and p_day + time '00:00' + interval '24h' and
deviceid = p_device and
status = 'Ok'
) and
deviceid = p_device;
select energy
into v_firstEnergy
from power_measurement_t
where time = (
select min(time)
from power_measurement_t
where time between p_day + time '00:00' and p_day + time '00:00' + interval '24h' and
deviceid = p_device and
status = 'Ok'
) and
deviceid = p_device;
v_total := v_lastEnergy - v_firstEnergy;
return v_total;
end;
$$;