Joins with grouping · Junções com agrupamento
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.
Relatórios: joins com agrupamento
O verdadeiro poder vem de combinar o que você aprendeu: unir duas tabelas, agrupar as linhas unidas e resumir cada grupo com um agregado.
Um relatório comum é "quanto cada cliente gastou?" — una clientes aos seus pedidos, agrupe por cliente e SUM os totais.
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.
Uma linha 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;
Lendo na ordem: una as tabelas, agrupe as linhas por cliente, então para cada grupo conte os pedidos e some os totais.
Common mistakes
- Join first, then
GROUP BYto summarise the joined rows. - Qualify a column with its table name when both tables share it.
Erros comuns
- Una primeiro, depois
GROUP BYpara resumir as linhas unidas. - Qualifique uma coluna com seu nome de tabela quando ambas as tabelas a compartilham.
Joining tables · Juntando tabelas
An inner join drops rows that have no match. · Um inner join descarta linhas que não têm correspondência.
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 tem pedidos, exiba sua name, seu número de pedidos como orders e seu gasto total (2 d.p.) como spent. Junte, agrupe por customer.id e ordene por name.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Um INNER JOIN escondeu Ben e Dan, que não têm pedidos. Use um LEFT JOIN para manter todo o cliente, e COUNT(orders.id) para que um cliente sem pedidos mostre 0. Ordene por name.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.