Skip to content
Advertisement

How to link all tables together?

I need to list countries in which there are customers, the number of customers, the number of orders, and the total amount of money spent by customers from the country. Using w3school database, I calculated separately each country, number of customers, number of orders and total amount spent, but I don’t know how to link all together.

I have just started to study SQL.

Table for number of customers:

SELECT country, count(*) as 'number of customer' 
FROM [Customers]
group by country

Number of orders by country:

SELECT Country, count(*) as 'number of order' 
FROM Orders, Customers
where orders.customerID=customers.CustomerID
group by country

Total amount spent by country:

SELECT Country, sum(price*quantity) as 'total price paid' 
FROM Orders, Customers, orderDetails, Products
where orders.customerID=customers.CustomerID 
and orders.OrderID=orderDetails.OrderID 
and orderDetails.productID=products.ProductID
group by country

Advertisement

Answer

First you must learn to use proper joins (using the JOIN keyword and an ON clause) and not this old style (using the WHERE clause).
Also it’s a good practice to alias the tables.
Now you have to join all the tables and count the distinct values of the columns like this:

SELECT 
  c.Country, 
  (SELECT COUNT(*) FROM Customers WHERE Country = c.Country) as 'number of customer',
  COUNT(DISTINCT o.OrderID) as 'number of order' 
  SUM(od.price * od.quantity) as 'total price paid' 
FROM Customers c 
INNER JOIN Orders o ON c.CustomerID = o.CustomerID 
INNER JOIN orderDetails od ON ON o.OrderID = od.OrderID
INNER JOIN Products p ON od.productID = p.ProductID
GROUP BY c.Country

I used the qualifier od for price and quantity because I believe that they are coluns of the table orderDetails.
Or with LEFT JOINs:

SELECT 
  c.Country, 
  COUNT(DISTINCT c.customerID) as 'number of customer',
  COUNT(DISTINCT o.OrderID) as 'number of order' 
  COALESCE(SUM(od.price * od.quantity), 0) as 'total price paid' 
FROM Customers c 
LEFT JOIN Orders o ON c.CustomerID = o.CustomerID 
LEFT JOIN orderDetails od ON ON o.OrderID = od.OrderID
LEFT JOIN Products p ON od.productID = p.ProductID
GROUP BY c.Country
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement