updating a field with a SUM from another table - Mailing list pgsql-sql

From Jeff Kowalczyk
Subject updating a field with a SUM from another table
Date
Msg-id pan.2003.09.23.16.15.53.274637@yahoo.com
Whole thread Raw
List pgsql-sql
My SQL is apparently a bit rusty, can anyone advise how to refactor
this updatecharges query to work? I need to update a total-charges field
in my orders table with the sum of the line-item charges in another table.
The tables are related by the orderid column.

Thanks for any help you can provide with updatecharges.

Query: updatecharges (query I'm having trouble with)
--------------------
UPDATE orders
RIGHT JOIN orderchargetotals
ON orders.orderid = orderchargetotals.orderid
SET orders.chargeasbilled = orderchargetotals.orderchargeasbilled;

Query: orderchargetotals
------------------------
SELECT ordercharges.orderid,
SUM(ordercharges.orderchargeasbilled) AS orderchargeasbilled
FROM ordercharges
GROUP BY orderid
ORDER BY orderid;

Table: orders
-------------
orderid, chargeasbilled, field1, field2, ...

Table: ordercharges
-------------------
orderchargeid, orderid, chargecode, ordercharge

BTW, I do know its counter to relational precepts to store a total one
could calculate at query-time, but I have reasons to do so at the the
moment.



pgsql-sql by date:

Previous
From: Tom Lane
Date:
Subject: Re: pl/pgsql, cursors and C function
Next
From: Tomasz Myrta
Date:
Subject: Re: pl/pgsql, cursors and C function