postgresql group by 和inner join
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24570932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
postgresql group by and inner join
提问by wonderbummer
I want a query in SQL which does INNER JOIN
and GROUP BY
at the same time. I tried the following which doesn't work:
我想在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;
Thank you in advance!
先感谢您!
回答by Rapha?l Althaus
First, GROUP BY
comes at the end of the query (just before order by
or having
clauses if you have some).
首先,GROUP BY
出现在查询的末尾(就在order by
orhaving
子句之前,如果有的话)。
Then, all fields in the select which are not in an aggregation function must be in the group by clause.
然后,select 中所有不在聚合函数中的字段都必须在 group by 子句中。
so
所以
SELECT customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY customer.first_name;
But customers with same first_name will be grouped, which is probably not really what you want.
但是具有相同 first_name 的客户将被分组,这可能不是您真正想要的。
so rather
所以相反
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;
回答by dnoeth
You want to group by the customer_id, but get the first_name?
您想按 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;
You might also do the aggregation in a Derived Table, then you can get additional columns from customer:
您也可以在派生表中进行聚合,然后您可以从客户那里获得额外的列:
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