How to obtain the sum of the values ​​per identifier and update the existing records in another table

advertisements

I have two tables like:

ID          |    TRAFFIC
fd56756     |      4398
645effa     |    567899
894fac6     |    611900
894fac6     |    567899

and

USER        |      ID         |    TRAFFIC
andrew      |    fd56756      |       0
peter       |    645effa      |       0
john        |    894fac6      |       0

I need to get SUM ("TRAFFIC") from first table AND set column traffic to the second table where first table ID = second table ID. ID's from first table are not unique, and can be duplicated.
How can I do this?


Table names from your later comment. Chances are, you are reporting table and column names incorrectly.

UPDATE users u
SET    "TRAFFIC" = sub.sum_traffic
FROM  (
   SELECT "ID", sum("TRAFFIC") AS sum_traffic
   FROM   stats.traffic
   GROUP  BY 1
   ) sub
WHERE u."ID" = sub."ID";

Aside: It's unwise to use mixed-case identifiers in Postgres. Use legal, lower-case identifiers, which do not need to be double-quoted, to make your life easier. Start by reading the manual here.