2012-03-04 3 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 
... 

이 같은 쿼리는 지역에있는 고객의 수를 들어 트릭

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 

을해야

Area1 Count_of_customers 
Area2 Count_of_customers 
.... 

답변

3

AreaID (NO 입력 매개 변수)로 그룹화 고객의 수 , 다음을 수행 할 수 있습니다.

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