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.
דוחות: חיבורים עם קבוצה
הכוח האמיתי נובע משילוב מה שלמדת: חבר שתי טבלאות, קבץ את השורות המחוברים, ו-סיכם כל קבוצה באמצעות פונקציית סכום.
דוח נפוץ הוא "כמה בילה כל לקוח?" – חבר את הלקוחות להזמנות שלהם, קבץ לפי לקוח, וחבר 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. · לחץ על הרץ כדי לראות את התוצא כאן.