2012-03-04 196 views
0

查詢所有SQL大師的簡單問題:我有以下表結構(不包括不相關的列);總查詢的SQL查詢

Area -- AreaID, AreaName 
District -- DistrictID, DistrictName, AreaID 
Office -- OfficeID, OfficeName, DistrictID 
Customer -- CustomerID, OfficeID 

我需要能夠得到給予areaID表示作爲輸入參數的客戶在辦公室的計數,由區,然後通過Distric分組;

DistrictID1 DistrictName1 Count_of_customers 
DistrictID2 DistrictName1 Count_of_customers 
... 

客戶通過areaID表示(無輸入參數)分組

Area1 Count_of_customers 
Area2 Count_of_customers 
.... 

回答

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