我的桌子
CREATE TABLE Customers (
id SERIAL PRIMARY KEY,
firstname VARCHAR(50),
lastname VARCHAR(50)
);
CREATE TABLE Payments (
id SERIAL PRIMARY KEY,
amount INT,
customer_id INT,
CONSTRAINT fk_CustomerPayment FOREIGN KEY (customer_id) REFERENCES Customers (id)
);
我希望获得所有客户的总付款金额。这是我的尝试:
SELECT SUM(p.amount)
FROM Customers c
JOIN Payments p
ON c.id = p.customer_id
GROUP BY p
答案 0 :(得分:3)
select sum(p.amount) as total
from
customers c
inner join
payments p on c.id = p.customer_id
如果payments.customer_id
中可以有空值,则连接条件将排除它们。
没有加入会更便宜:
select sum(amount) as total
from payments
where customer_id is not null
答案 1 :(得分:0)
从查询中删除分组..
SELECT SUM(p.amount)
FROM Customers c
JOIN Payments p
ON c.id = p.customer_id