Défi
Énoncé
Deux tables existent : clients(id INT, nom TEXT) et commandes(id INT, client_id INT, total NUMERIC). Écrire une requête SQL qui retourne, pour chaque client ayant au moins une commande, son nom et la somme de ses total. Le résultat doit être trié par total décroissant.
Contraintes
- Utiliser
INNER JOIN(les clients sans commande ne doivent pas apparaître). - Utiliser
GROUP BYsur l'identifiant ou le nom du client. - Nommer la colonne agrégée
total_commandes. - Trier par
total_commandes DESC. - PostgreSQL 15+.
Exemple
Jeu de données :
CREATE TABLE clients (id INT, nom TEXT);
INSERT INTO clients VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Camille');
CREATE TABLE commandes (id INT, client_id INT, total NUMERIC);
INSERT INTO commandes VALUES
(1, 1, 120.00),
(2, 1, 80.00),
(3, 2, 200.00),
(4, 3, 50.00),
(5, 3, 75.00);
Requête :
SELECT c.nom, SUM(o.total) AS total_commandes
FROM clients c
INNER JOIN commandes o ON o.client_id = c.id
GROUP BY c.id, c.nom
ORDER BY total_commandes DESC;
Résultat attendu :
nom | total_commandes
---------+-----------------
Bob | 200.00
Alice | 200.00
Camille | 125.00
(3 lignes)