Joins with grouping · Joins พร้อมการจัดกลุ่ม
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.
รายงาน: การ join พร้อมการ grouping
พลังที่แท้จริงมาจากการรวมสิ่งที่คุณเรียนรู้: join ตารางสองตาราง, group แถวที่ join แล้ว และ สรุป แต่ละกลุ่มด้วยฟังก์ชัน aggregate
รายงานที่พบบ่อยคือ "ลูกค้าแต่ละคนใช้จ่ายไปเท่าไหร่?" — join ลูกค้าเข้ากับคำสั่งซื้อ их, group ตามลูกค้า และ 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;
อ่านตามลำดับ: join ตาราง, group แถวตามลูกค้า จากนั้นสำหรับแต่ละกลุ่มนับจำนวนคำสั่งซื้อและบวกผลรวมทั้งหมด
Common mistakes
- Join first, then
GROUP BYto summarise the joined rows. - Qualify a column with its table name when both tables share it.
ข้อผิดพลาดทั่วไป
- Join ก่อน แล้ว
GROUP BYเพื่อสรุปข้อมูลจากแถวที่ join แล้ว - ระบุชื่อคอลัมน์ด้วยชื่อตารางเมื่อทั้งสองตารางมีชื่อคอลัมน์ซ้ำกัน
Joining tables · การเชื่อมต่อตาราง
An inner join drops rows that have no match. · Inner join จะทิ้งแถวที่ไม่มี คู่จับคู่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 ได้ซ่อน Ben และ Dan ซึ่งไม่มีคำสั่งซื้อ ใช้ LEFT JOIN เพื่อรักษา ทุก ลูกค้า, และ COUNT(orders.id) เพื่อให้ลูกค้าที่ไม่มีคำสั่งซื้อแสดง 0 เรียงลำดับตาม name
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่