Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql group by and inner join

Tags:

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:

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!

like image 647
wonderbummer Avatar asked Jul 04 '14 09:07

wonderbummer


People also ask

Can you inner join after GROUP BY?

You can use GROUP BY with INNER JOIN in SQL Server to group the results according to the values in a list of one or more column expressions.

What does GROUP BY do in Postgres?

The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement to group together those rows in a table that have identical data. This is done to eliminate redundancy in the output and/or compute aggregates that apply to these groups.

Where do I go after GROUP BY?

GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause. In the query, GROUP BY clause is placed before ORDER BY clause if used any.

Is GROUP BY and aggregate function?

The Group By statement is used to group together any rows of a column with the same value stored in them, based on a function specified in the statement. Generally, these functions are one of the aggregate functions such as MAX() and SUM().


2 Answers

First, GROUP BY comes at the end of the query (just before order by or having clauses if you have some).

Then, all fields in the select which are not in an aggregation function must be in the group by clause.

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.

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; 
like image 171
Raphaël Althaus Avatar answered Oct 07 '22 15:10

Raphaël Althaus


You want to group by the customer_id, but get the 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 
like image 37
dnoeth Avatar answered Oct 07 '22 15:10

dnoeth