I have the following tables.
Customer_table
Customer_ID | Last name | First Name | City_ID | Region_ID | Country_IDCountry_table
Country_ID | CountryRegion_table
Region_ID | Region | Country_IDCity_table
City_ID | City | Region_ID | Country_ID
I need to find the number of customers city-wise,ie, for all countries, for all regions in the countries, for all cities in the region, i need to get the no. of customers in each city.
For example, I wrote the following SQL to get the no. of customers in each country:
SELECT a.country_id , b.country,count(*)
FROM Customer_Table a INNER JOIN Country_Table b
ON a.country_id = b.country_id
GROUP BY b.country , b.country_id ;
and to get the no. of customers in each region for a particular country:
SELECT a.region_id , b.region , count(*)
FROM Customers_table a INNER JOIN Region_Table b
ON a.region_id = b.region_id
WHERE a.country_id ='USA' AND b.country_id ='USA'
GROUP BY region_id , country ;
What I need to find is the number of customers city-wise,ie, for all countries, for all regions in the countries, for all cities in the region, i need to get the no. of customers in each city, something like
Country | Region | City | no.of customers
USA | CA | San Francisco | 53
USA | CA | Los Angeles | 45
USA | CA | Sacramento | 16
USA | WA | Seattle | 46
USA | WA | Olympia | 9
UK | England | London | 89
UK | England | Nottingham | 71
UK | Wales | Cardiff | 69
UK | Wales | Newport | 23
..................and so on for other countries.
Your tables have redundant info
since they are linked, each table only needs to reference its direct parent and not all parents in the hierarchy ..
so customer only needs to reference the city, city only the region, region only the country