NoBullMan
NoBullMan

Reputation: 2188

SQL query for total

a simple question for all you SQL gurus: I have the following table structures (not including irrelevant columns);

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

I need to be able to get a count of customers in offices, grouped by Area and then by Distric, given an AreaID as input parameter;

DistrictID1 DistrictName1 Count_of_customers
DistrictID2 DistrictName1 Count_of_customers
...

and a count of customers grouped by AreaID (no input parameter)

Area1 Count_of_customers
Area2 Count_of_customers
....

Upvotes: 0

Views: 59

Answers (1)

Kibbee
Kibbee

Reputation: 66162

A query like this should do the trick

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

For the count of customers in the area, you can do the following

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

Upvotes: 3

Related Questions