DROP VIEW v_consumption_energy_last_update;

CREATE OR REPLACE VIEW v_consumption_energy_last_update
AS WITH last_update AS (
         SELECT b.building_name,
            c.addr,
            max(c.time_utc) AS last_update
           FROM energetics.consumption_energy_consumption c
             JOIN energetics.consumption_energy_devices d ON c.addr::text = d.addr::text
             JOIN energetics.consumption_energy_buildings b ON d.building_id = b.id
          GROUP BY b.building_name, c.addr
        ), last_not_zero AS (
         SELECT consumption_energy_consumption.addr,
            max(consumption_energy_consumption.time_utc) AS last_not_zero_value
           FROM energetics.consumption_energy_consumption
          WHERE consumption_energy_consumption.value > 0::numeric
          GROUP BY consumption_energy_consumption.addr
        )
 SELECT lu.building_name,
    lu.last_update,
    lu.addr,
        CASE
            WHEN lnz.last_not_zero_value = lu.last_update THEN NULL::timestamp without time zone
            ELSE lnz.last_not_zero_value
        END AS zero_values_after
   FROM last_update lu
     LEFT JOIN last_not_zero lnz ON lu.addr::text = lnz.addr::text;
