实现说明
这个文件依次执行 SELECT / INSERT / UPDATE / CREATE 语句,涉及 orders、customer_balances。
从子句角度看,用到了:WHERE 按条件筛出这条语句真正触碰的行;用 COUNT、SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。
常见问题
这里用到哪些关系?
orders、customer_balances。
核心语句
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
);
代码示例
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;