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!
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.
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.
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.
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().
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With