Update From Grouped Derived Table

Aggregate rows in a grouped subquery and join it in UPDATE ... FROM, so per-customer totals land in one deterministic statement.

SqlData Integrity

Code

snippet
CREATE TABLE orders (
    order_id int PRIMARY KEY,
    customer text NOT NULL,
    cents    int NOT NULL,
    billed   boolean NOT NULL DEFAULT false
);

CREATE TABLE customer_balances (
    customer    text PRIMARY KEY,
    open_cents  int NOT NULL DEFAULT 0,
    open_orders int NOT NULL DEFAULT 0
);

INSERT INTO orders (order_id, customer, cents) VALUES
    (1, 'ada', 1200), (2, 'ada', 800), (3, 'lin', 500);

-- 预置余额行:customer_balances 先有行,UPDATE 才有落点
INSERT INTO customer_balances (customer) VALUES
    ('ada'), ('lin'), ('leo');

-- UPDATE ... FROM 聚合派生表:每个 customer 恰好一行,整列一次赋值
UPDATE customer_balances b
SET open_cents  = agg.total,
    open_orders = agg.cnt
FROM (
    SELECT customer,
           SUM(cents)::int AS total,
           COUNT(*)::int   AS cnt
    FROM orders
    WHERE NOT billed
    GROUP BY customer
) agg
WHERE b.customer = agg.customer;

SELECT customer, open_cents, open_orders
FROM customer_balances
ORDER BY customer;

DROP TABLE customer_balances, orders;

How the snippet works

What runs here is SELECT / INSERT / UPDATE / CREATE — orders and customer_balances are the objects involved.

Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

Run the statement against the orders table.

Statements that matter

UPDATE customer_balances b
SET open_cents  = agg.total,
    open_orders = agg.cnt
FROM (
    SELECT customer,
           SUM(cents)::int AS total,
           COUNT(*)::int   AS cnt
    FROM orders
    WHERE NOT billed
    GROUP BY customer
) agg
WHERE b.customer = agg.customer;
CREATE TABLE orders (
    order_id int PRIMARY KEY,
    customer text NOT NULL,
    cents    int NOT NULL,
    billed   boolean NOT NULL DEFAULT false
);
CREATE TABLE customer_balances (
    customer    text PRIMARY KEY,
    open_cents  int NOT NULL DEFAULT 0,
    open_orders int NOT NULL DEFAULT 0
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`orders`, `customer_balances`.