Joins with grouping · Joins avec groupement
Reports: joins with grouping
The real power comes from combining what you have learned: join two tables, group the joined rows, and summarise each group with an aggregate.
A common report is "how much has each customer spent?" — join customers to their orders, group by customer, and SUM the totals.
Rapports : joints avec regroupement
La véritable puissance provient de la combinaison de ce que vous avez appris : joindre deux tables, regrouper les lignes jointes, et résumer chaque groupe avec une agrégation.
Un rapport courant est « combien a dépensé chaque client ? » — joignez les clients à leurs commandes, regroupez par client, et SUM les totaux.
One row per customer
Reading it in order: join the tables, group the rows by customer, then for each group count the orders and add up the totals.
Une ligne par client
SELECT customer.name,
COUNT(*) AS orders,
ROUND(SUM(orders.total), 2) AS spent
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id
GROUP BY customer.id
ORDER BY customer.name;
En le lisant dans l'ordre : joignez les tables, regroupez les lignes par client, puis pour chaque groupe comptez les commandes et additionnez les totaux.
Common mistakes
- Join first, then
GROUP BYto summarise the joined rows. - Qualify a column with its table name when both tables share it.
Erreurs courantes
- Joignez d'abord, puis
GROUP BYpour résumer les lignes jointes. - Qualifiez une colonne avec son nom de table si les deux tables partagent le même nom.
Joining tables · Jointure de tables
An inner join drops rows that have no match. · Un inner join élimine les lignes qui n'ont aucune correspondance.
For each customer who has orders, show their name, their number of orders as orders, and their total spend (2 d.p.) as spent. Join, group by customer.id, and order by name. · Pour chaque client qui a des commandes, affichez sa name, son nombre de commandes en tant que orders, et son dépense totale (2 décimales) en tant que spent. Join, group by customer.id, and order by name.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
An INNER JOIN hid Ben and Dan, who have no orders. Use a LEFT JOIN to keep every customer, and COUNT(orders.id) so a customer with no orders shows 0. Order by name. · Un INNER JOIN masquait Ben et Dan, qui n'ont pas de commandes. Utilisez un LEFT JOIN pour conserver tous les clients, et COUNT(orders.id) pour qu'un client sans commandes affiche 0. Order by name.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.