繁体   English   中英

需要帮助编写SQL查询

[英]Need help writing a SQL query

我有下表。

客户表
客户编号| 姓| 名| City_ID | Region_ID | Country_ID

Country_table
Country_ID | 国家

Region_table
Region_ID | 地区| Country_ID

City_table
City_ID | 城市| Region_ID | Country_ID

我需要找到按城市划分的客户数量,即,对于所有国家/地区,该国家/地区的所有地区,该地区的所有城市的客户,我都需要获得编号。 每个城市的客户数量。

例如,我编写了以下SQL以获得否。 每个国家/地区的客户数量:

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 ;

并得到没有。 每个地区在特定国家/地区的客户数量:

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 ;

我需要查找的是按城市划分的客户数量,即,对于所有国家/地区,该国家/地区的所有地区,该地区所有城市的客户,我都需要获得该数字。 每个城市的客户数量

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.

您的表中有多余的信息

由于它们是链接的,因此每个表仅需要引用其直接父级,而不必引用层次结构中的所有父级。

因此客户只需要参考城市,城市仅参考区域,区域仅参考国家

SELECT
    Country_Table.Country,
    Region_Table.Region,
    City_Table.City,
    Count(Customer_Id) AS Customers
FROM
    Country_Table
    INNER JOIN Region_Table ON Region_Table.Country_Id = Country_Table.Country_Id
    INNER JOIN City_Table ON City_Table.Region_Id = Region_Table.Region_Id
    INNER JOIN Customer_Table ON Customer_Table.City_Id = City_Table.City_Id
GROUP BY
    Country_Table.Country,
    Region_Table.Region,
    City_Table.City

尝试这个 :

select Country,Region,City,count(Customer_ID)
from Customer_table as cust
inner join  Country_table on Country_ID=cust.Country_ID
inner join Region_table on Region_ID=cust.Region_ID
inner join Region_table on City_ID=cust.City_ID
group by country,Region,City

对于SQL Server:

SELECT Country, Region, City, COUNT(Customer_ID) as [no.of customers]
FROM Country_Table
INNER JOIN Region_Table ON Country_Table.Country_ID = Region_Table.Country_ID
INNER JOIN City_Table ON City_Table.Region_ID = Region_Table.Region_ID
INNER JOIN Customer_Table ON Customer_Table.City_ID = City_Table.City_ID
GROUP BY Country, Region, City;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM