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. · يحذف الـ 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. · اضغط تشغيل لرؤية المخرجات هنا.
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. · اضغط تشغيل لرؤية المخرجات هنا.