So I have a table which will be keeping an average energy usage for specific stores at specific temperatures.
Store + Temperature(Integer) is not in table -> Add to the table
Store + Temperature is in table -> Use two of the rows parameters
to find the new average and update the row
If my table looks like this
CREATE TABLE public.temperatures (
temp_id serial NOT NULL PRIMARY KEY,
temp_station_id integer,
temp_value double precision,
temp_curr_kwh double precision,
temp_value_added integer,
temp_kwh_year_1 double precision (default 0)
)
I found this answer similar to my question but it is for mySQL, would this work for postgres?
ALTER TABLE temperatures ADD UNIQUE (temp_station_id, temp_value);
and execute the following statement
INSERT INTO temperatures (temp_station_id, temp_value, temp_curr_kwh)
SELECT temp_station_id, temp_value, temp_curr_kwh
FROM temperatures
WHERE temp_station_id = 'STATION_NAME_VAR' AND
temp_curr_kwh = 'KWH_VALUE_VAR'
ON DUPLICATE KEY UPDATE temp_curr_kwh = ((temp_curr_kwh * temp_value_added) + KWH_VALUE_VAR) / (temp_value_added + 1),
temp_value_added = temp_value_added + 1;
So if the station and temperature exist, it takes the old temp_curr_kwh
(average) multiplies it by the number of values added so far temp_curr_kwh * temp_value_added
then add the new kwh value and then divide the new sum by the temp_value_added + 1
Before I try the code I wanted to check to see if this could be optimized or done differently?