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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:32:04  来源:igfitidea点击:

postgresql group by and inner join

sqlpostgresqlgroup-byinner-join

提问by wonderbummer

I want a query in SQL which does INNER JOINand GROUP BYat 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 BYcomes at the end of the query (just before order byor havingclauses if you have some).

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

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