Joins with grouping · グループ化付きジョイン
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.
レポート: グループ化付きジョイン
真の力は、これまでに学んだことを組み合わせることで発揮されます。2つのテーブルをジョインし、結合した行をグループ化し、各グループを集計関数で要約することです。
一般的なレポートとして「各顧客はどれだけの金額を消費したか?」があります。顧客とその注文をジョインし、顧客ごとにグループ化して、SUM で合計を算出します。
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.
每位客户一行
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;
順に読み解くと:テーブルをジョインし、顧客ごとに行をグループ化し、その後各グループについて注文数をカウントし、合計を足し合わせます。
Common mistakes
- Join first, then
GROUP BYto summarise the joined rows. - Qualify a column with its table name when both tables share it.
よくあるミス
- まずジョインを行い、次に
GROUP BYを用いて結合した行を要約します。 - 両方のテーブルで同じカラムがある場合は、カラム名にテーブル名を付与します。
Joining tables · テーブルのジョイン
An inner join drops rows that have no match. · インナージョインでは、一致する行がない行は除外される。
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. · 注文を持つ各顧客について、顧客name、注文数orders、総消費額(小数点以下2桁:spent)を表示する。ジョインし、customer.id でグループ化、name で並べ替える。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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. · INNER JOIN は注文のないベンとダンを除外した。LEFT JOIN を使用して全顧客を保持し、COUNT(orders.id) を用いて注文のない顧客には0 を表示する。name で並べ替える。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。