我有两张桌子:
customers(id,first_name,last_name,email)
orders (id,order_date,amount,customer_id)
orders表中的customer_id是customers表中id的外键
我试图在
PostgreSQL
上运行以下代码,并得到一个错误:SELECT first_name,last_name,order_date, sum(amount)
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
GROUP BY orders.customer_id;
有人能告诉我我的密码怎么了吗?
最佳答案
只需按select
中未聚合的所有列进行聚合。此外,还要限定列名:
SELECT c.first_name, c.last_name, o.order_date, sum(o.amount)
FROM customers c INNER JOIN
orders o
ON c.id = o.customer_id
GROUP BY c.first_name, c.last_name, o.order_date;
如果需要每个客户名称的总和,请删除
order_date
:SELECT c.first_name, c.last_name, sum(o.amount)
FROM customers c INNER JOIN
orders o
ON c.id = o.customer_id
GROUP BY c.first_name, c.last_name;
关于sql - 按 zip 分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48313307/