0

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?

pozs
  • 34,608
  • 5
  • 57
  • 63
Eric G
  • 928
  • 1
  • 9
  • 29
  • I don't see a default value for `temp_value_added`. – Bacon Bits Jan 22 '16 at 15:41
  • I dont get why the question gets marked as a duplicate for an MYSQL question where the 'ON DUPLICATE` doesnt work with postgres. Btw I'm on postgres 9.4.5. – Eric G Jan 22 '16 at 15:46
  • Duplicate, but not for the question for MySQL (as @Hogan linked). For PostgreSQL, see http://stackoverflow.com/q/17267417/1499698 – pozs Jan 22 '16 at 16:36
  • Also: http://stackoverflow.com/questions/17267417/how-do-i-do-an-upsert-merge-insert-on-duplicate-update-in-postgresql –  Jan 22 '16 at 16:45
  • @pozs -- thanks... I totally read this as a MySQL question -- not sure how. – Hogan Jan 22 '16 at 17:50

0 Answers0