UPDATE consumption c SET
	kwh = raw.a_value,
	data_source_id = raw.data_source_id
  FROM (
	-- First part takes most recent (by line) of the duplicated entries
	SELECT batch_id,data_source_id,building_id,energy_type_id,meter_id,a_datetime,a_value
	  FROM consumption_raw
	  JOIN (
		SELECT max(line_number) line_number FROM consumption_raw
		 WHERE batch_id=123
		 GROUP BY batch_id,data_source_id,building_id,energy_type_id,meter_id,a_datetime
	  ) ml USING (line_number)
	 WHERE batch_id=123
	UNION ALL
	SELECT batch_id,data_source_id,building_id,energy_type_id,meter_id,a_datetime,a_value
	  FROM consumption_raw
	 WHERE false
  ) raw
 WHERE c.building_id = raw.building_id
   AND c.meter_id = raw.meter_id
   AND c.energy_type_id = raw.energy_type_id
   AND c.a_datetime = raw.a_datetime
   AND coalesce(c.kwh, 0.0) != raw.a_value;
