2014-07-04 13 views
7

Voglio una query in SQL che fa INNER JOIN e GROUP BY allo stesso tempo. Ho provato quanto segue che non funziona:postgresql group by e inner join

SELECT customer.first_name, SUM(payment.amount) 
FROM customer 
GROUP BY customer.customer_id 
INNER JOIN payment 
ON payment.customer_id = customer.customer_id; 

Grazie in anticipo!

risposta

8

Primo, GROUP BY arriva alla fine della query (poco prima delle order by o delle clausole having se ne avete).

Quindi, tutti i campi della selezione che non sono in una funzione di aggregazione devono essere inclusi nella clausola group by.

così

SELECT customer.first_name, SUM(payment.amount) 
FROM customer 
INNER JOIN payment 
ON payment.customer_id = customer.customer_id 
GROUP BY customer.first_name; 

Ma i clienti con lo stesso first_name saranno raggruppati, che probabilmente non è veramente quello che vuoi.

in modo piuttosto

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

Grazie, questo è quello che ho cercato! Il [postgres tutorial] (http://www.postgresqltutorial.com/postgresql-group-by/) mi ha confuso, perché dicono che devi mettere la clausola 'GROUP BY' subito dopo' FROM' o 'WHERE'clause . – wonderbummer

7

si desidera raggruppare dal customer_id, ma ottiene il 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; 

Si potrebbe anche fare l'aggregazione in una tabella derivata, allora si può ottenere colonne aggiuntive da parte del cliente:

SELECT customer.first_name, SumPayment 
FROM customer 
INNER JOIN 
(
    SELECT customer_id, 
      SUM(payment.amount) AS SumPayment 
    GROUP BY customer_id 
    FROM payment 
) AS payment 
ON payment.customer_id = customer.customer_id