一个简单的问题,适用于所有SQL大师:我有以下表结构(不包括不相关的列);
Area -- AreaID, AreaName
District -- DistrictID, DistrictName, AreaID
Office -- OfficeID, OfficeName, DistrictID
Customer -- CustomerID, OfficeID
我需要能够获得办公室中的客户数量,按区域分组,然后按Distric分组,给定AreaID作为输入参数;
DistrictID1 DistrictName1 Count_of_customers
DistrictID2 DistrictName1 Count_of_customers
...
和按AreaID(无输入参数)分组的客户数
Area1 Count_of_customers
Area2 Count_of_customers
....
答案 0 :(得分:3)
像这样的查询应该可以解决问题
Select D.DistrictID, D.DistrictName, Count(*)
FROM District AS D
INNER JOIN Office AS O
ON D.DistrictID = O.DistrictID
INNER JOIN Customers AS C
ON O.OfficeID = C.OfficeID
WHERE D.AreaID = 1234
GROUP BY D.DistrictID, D.DistrictName
对于该地区的客户数量,您可以执行以下操作
Select A.AreaID,A.AreaName, Count(*)
FROM Area AS A
INNER JOIN District AS D
ON A.AreaID = D.AreaID
INNER JOIN Office AS O
ON D.DistrictID = O.DistrictID
INNER JOIN Customers AS C
ON O.OfficeID = C.OfficeID
GROUP BY A.AreaID,A.AreaName