Joins with grouping · Uniones con agrupación
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.
Informes: uniones con agrupación
La verdadera potencia surge al combinar lo que has aprendido: unir dos tablas, agrupar las filas unidas y resumir cada grupo con una función de agregación.
Un informe común es "¿cuánto ha gastado cada cliente?" — une los clientes con sus pedidos, agrupa por cliente y calcula la SUM de los totales.
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.
Una fila por cliente
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;
Leyéndolo en orden: une las tablas, agrupa las filas por cliente y, luego, para cada grupo cuenta los pedidos y suma los totales.
Common mistakes
- Join first, then
GROUP BYto summarise the joined rows. - Qualify a column with its table name when both tables share it.
Errores comunes
- Une primero, luego aplica
GROUP BYpara resumir las filas unidas. - Califica una columna con su nombre de tabla cuando ambas tablas la comparten.
Joining tables · Unión de tablas
An inner join drops rows that have no match. · Una unión interna elimina las filas que no tienen correspondencia.
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. · Para cada cliente que tenga pedidos, muestre su name, su número de pedidos como orders y su gasto total (2 decimales) como spent. Realice la unión, agrupe por customer.id y ordene por name.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Una INNER JOIN ocultó a Ben y Dan, que no tienen pedidos. Utilice una LEFT JOIN para mantener todos los clientes, y COUNT(orders.id) para que un cliente sin pedidos muestre 0. Ordene por name.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.