I am trying to update a column based on a few conditions, using a calculation.
The theory I am using is as follows; If column1 contains 'string' then 'calculation of column2 and column3' gets put in column4.
The calculation works, but I am struggling to find a way to UPDATE a column by using these IF conditions and a SUM.
I have searched stack and postgres documentation. I see that there are a number of aggregate errors but none specifically solve this problem.
UPDATE table1
SET "column4" = CASE
WHEN "column1" ILIKE '%Y%' THEN SUM(CAST("column2" AS
numeric(4,2))) / SUM(CAST("column3" AS numeric(4,2)))
END;
The error which I am getting is as follows;
ERROR: aggregate functions are not allowed in UPDATE LINE 7: WHEN "column1" ILIKE '%Y%' THEN (SUM(CAST("...
An aggregate may not appear in the set list of an UPDATE statement. But SQL doesn't always agree that it should be simple. Let's setup a contrived example using a data set of Airport Gate information from San Francisco Airport.
We cannot use the WHERE clause with aggregate functions because it works for filtering individual rows. In contrast, HAVING can works with aggregate functions because it is used to filter groups.
Do your calculations in a common table expression:
WITH cte_avg AS (
SELECT SUM(CAST("column2" AS numeric(4,2))) / SUM(CAST("column3" AS numeric(4,2))) AS avg
FROM table1
)
UPDATE table1
SET "column4" = cte_avg.avg
FROM cte_avg
WHERE "column1" LIKE '%Y%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With