postgresql group by和inner join

时间:2014-07-04 09:23:39

标签: sql postgresql group-by inner-join

我希望SQL中的查询同时执行INNER JOINGROUP BY。我尝试了以下哪些不起作用:

SELECT customer.first_name, SUM(payment.amount)
FROM customer
GROUP BY customer.customer_id
INNER JOIN payment
ON payment.customer_id = customer.customer_id;

提前谢谢!

2 个答案:

答案 0 :(得分:17)

首先,GROUP BY出现在查询的末尾(如果你有一些话,就在order byhaving子句之前)。

然后,select中不在聚合函数中的所有字段必须在group by子句中。

所以

SELECT customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY  customer.first_name;

但具有相同first_name的客户将被分组,这可能不是您想要的。

所以相反

SELECT  customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY  customer.first_name, customer.customer_id;

答案 1 :(得分:9)

您希望按customer_id分组,但获取first_name?

SELECT customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY customer.customer_id, customer.first_name;

您也可以在派生表中进行聚合,然后您可以从客户那里获得其他列:

SELECT customer.first_name, SumPayment
FROM customer
INNER JOIN 
 (
   SELECT customer_id,
          SUM(payment.amount) AS SumPayment
   FROM payment
   GROUP BY customer_id
 ) AS payment
ON payment.customer_id = customer.customer_id