-- model shows the energy consumed per day per device

WITH total_energy AS (--/100 to get value in kWh
    SELECT 
        device_id,
        event_time::date AS date,
        MIN(value)::integer/100 AS min_value,
        MAX(value)::integer/100 AS max_value
    FROM "device-status-log"
    where code='EnergyConsumed'
    GROUP BY device_id, date
)

, energy_phase_A AS ( --in 
    SELECT 
        device_id,
        event_time::date AS date,
        MIN(value)::integer/100 AS min_value,
        MAX(value)::integer/100 AS max_value
    FROM "device-status-log"
    where code='EnergyConsumedA'
    GROUP BY device_id, date
)

, energy_phase_B AS (
    SELECT 
        device_id,
        event_time::date AS date,
        MIN(value)::integer/100 AS min_value,
        MAX(value)::integer/100 AS max_value
    FROM "device-status-log"
    where code='EnergyConsumedB'
    GROUP BY device_id, date
)

, energy_phase_C AS (
    SELECT 
        device_id,
        event_time::date AS date,
        MIN(value)::integer/100 AS min_value,
        MAX(value)::integer/100 AS max_value
    FROM "device-status-log"
    where code='EnergyConsumedC'
    GROUP BY device_id, date
)


SELECT 
    total_energy.device_id,
    total_energy.date,
    (total_energy.max_value-total_energy.min_value) as energy_consumed_kW,
    (energy_phase_A.max_value-energy_phase_A.min_value) as energy_consumed_A,
    (energy_phase_B.max_value-energy_phase_B.min_value) as energy_consumed_B,
    (energy_phase_C.max_value-energy_phase_C.min_value) as energy_consumed_C
FROM total_energy
JOIN energy_phase_A
	ON total_energy.device_id=energy_phase_A.device_id
	and total_energy.date=energy_phase_A.date
JOIN energy_phase_B
	ON total_energy.device_id=energy_phase_B.device_id
	and total_energy.date=energy_phase_B.date
JOIN energy_phase_C
	ON total_energy.device_id=energy_phase_C.device_id
	and total_energy.date=energy_phase_C.date;
