我希望SQL中的查询同时执行INNER JOIN
和GROUP 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;
提前谢谢!
答案 0 :(得分:17)
首先,GROUP BY
出现在查询的末尾(如果你有一些话,就在order by
或having
子句之前)。
然后,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