I have the following table in Postgres:
CREATE TABLE avg (
user_id INT,
numer DOUBLE PRECISION,
denom DOUBLE PRECISION,
frac DOUBLE PRECISION
);
I want to accomplish the following, and I'm having a hard time getting this into one query. Basically I want to be able to update some averages atomically, by separately updating the numerator and denominator, then compute and update the average frac in the same operation, based on the new values:
- Given params
aandb, I want to find the row for a givenuser_id, then I want to donumer += aanddenom += b, and calculatefrac = numer / denomfrom the new values ofnumeranddenom, then update the values ofnumer,denom, andfracin this row. - However, if there is no row for the requested
user_id, or if there is a row, but the values ofnumeranddenomare null, then I want to assume that the value of those sums is zero, in other words a new row should be inserted into the table, or an update operation should be performed if there is a row but the values are null, with the result being to setnumer = a,denom = b, andfrac = a / bfor theuser_id. - I want to ensure this all happens atomically.
There may be multiple numerators and denominators in a given table, hence the need to be able to do both insert (if the row doesn't exist) or update (if the row exists but the initial values of a specific numerator/denominator pair are null).