Här är ett allmänt exempel på hur man gör det.
UPDATE public.customer_value cv
SET total_value = sub_q.sum_val
FROM
(
SELECT SUM(order_amount) AS sum_val, o.customer_id
FROM public.orders AS o
GROUP BY o.customer_id
) AS sub_q
WHERE sub_q.customer_id = cv.customer_id;
Om du vill prova det här exemplet i sin helhet kan du skapa dummydata så här:
CREATE TABLE public.customer_value
(
customer_id int
, total_value numeric (10,2)
);
CREATE TABLE public.orders
(
customer_id int
, order_amount numeric(10,2)
);
INSERT INTO public.customer_value
(customer_id)
VALUES
(1)
, (2);
INSERT INTO public.orders
(customer_id, order_amount)
VALUES
(1, 10)
,(1, 10)
,(2, 7.5)
,(2, 7.5);