Joins พร้อมการจัดกลุ่ม
พลังที่แท้จริงมาจากการรวมสิ่งที่คุณเรียนรู้: join ตารางสองตาราง, group แถวที่ join แล้ว และ สรุป แต่ละกลุ่มด้วยฟังก์ชัน aggregate
A common report is "how much has each customer spent?" — join customers to their orders, group by customer, and SUM 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, customer.name
ORDER BY customer.name;
อ่านตามลำดับ: join ตาราง, group แถวตามลูกค้า จากนั้นสำหรับแต่ละกลุ่มนับจำนวนคำสั่งซื้อและบวกผลรวมทั้งหมด
An INNER JOIN ตัด Ben และ Dan ออกเพราะไม่มีคำสั่งซื้อ A LEFT JOIN รักษาลูกค้าทุกคนและใส่ NULL สำหรับคำสั่งซื้อที่ไม่ตรงกัน COUNT(*) จะนับบรรทัดนี้หนึ่งบรรทัด; COUNT(orders.id) ข้าม id NULL ของมันและให้ศูนย์อย่างถูกต้อง SUM คืนค่า NULL เมื่อไม่มีผลรวมที่ไม่ใช่ NULL ดังนั้นใช้ COALESCE(..., 0) สำหรับรายงานการใช้จ่ายศูนย์
เพื่อนับเฉพาะคำสั่งซื้อที่มีอย่างน้อย 25 โดยรักษาลูกค้าทุกคน ให้วางเงื่อนไขคำสั่งซื้อใน ON:
SELECT customer.name, COUNT(orders.id) AS qualifying_orders,
COALESCE(ROUND(SUM(orders.total), 2), 0) AS spent
FROM customer
LEFT JOIN orders ON customer.id = orders.customer_id AND orders.total >= 25
GROUP BY customer.id, customer.name
ORDER BY customer.name;
The result is Ada: 1 and 25; Ben: 0 and 0; Cara: 1 and 40; Dan: 0 and 0. Moving orders.total >= 25 to WHERE would remove Ben and Dan: their NULL totals do not satisfy that comparison. Group by the id as well as the name so two customers with the same name remain separate.
- Join ก่อน แล้ว
GROUP BYเพื่อสรุปข้อมูลจากแถวที่ join แล้ว - ระบุชื่อคอลัมน์ด้วยชื่อตารางเมื่อทั้งสองตารางมีชื่อคอลัมน์ซ้ำกัน
การเชื่อมต่อตาราง
Inner join จะทิ้งแถวที่ไม่มี คู่จับคู่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
สำหรับลูกค้าแต่ละคน ที่มีคำสั่งซื้อ แสดง name จำนวนคำสั่งซื้อเป็น orders และยอดใช้จ่ายรวม (2 ทศนิยม) เป็น spent เชื่อมต่อ, จัดกลุ่มโดย customer.id, และเรียงลำดับตาม name
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
INNER JOIN ได้ซ่อน Ben และ Dan ซึ่งไม่มีคำสั่งซื้อ ใช้ LEFT JOIN เพื่อรักษา ทุก ลูกค้า, และ COUNT(orders.id) เพื่อให้ลูกค้าที่ไม่มีคำสั่งซื้อแสดง 0 เรียงลำดับตาม name
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เก็บลูกค้าทุกคน รวมถึงผู้ที่ไม่มีการสั่งซื้อที่ qualify แสดง name, จำนวนคำสั่งซื้อที่มี total > 30 เป็น orders, และผลรวม theirs as spent (round to 2 d.p., or 0 if none). Order by name. Place the filter so unmatched customers survive.
คลิก Run เพื่อดูผลลัพธ์ที่นี่