I am working with Northwind Data Base(Microsoft Example) and i want to know total Sale of each Region.
tables for this example are (Region,Territories,EmployeeTerritories,Employees,Orders and OrderDetails)
And relations are:
- Region on to many Territories
- Territories on to many EmployeeTerritories
- EmployeeTerritories many to one Employees
- Employees on to many Orders
- Orders one to many OrderDetails
i know that i should to use Sub query but i dont know how.
select
*
from
Region R
inner join Territories T
on R.RegionID=T.RegionID
inner join EmployeeTerritories ET
on T.TerritoryID=ET.TerritoryID
inner join
(
select
E.EmployeeID,
E.FirstName,
E.LastName,
sum(OD.Quantity*OD.UnitPrice) as TotalEmployeeSale
from
Employees E
inner join Orders O
on E.EmployeeID=o.EmployeeID
inner join [Order Details] OD
on o.OrderID=OD.OrderID
Group by
E.EmployeeID,
E.FirstName,
E.LastName
)as ES on ET.EmployeeID=ES.EmployeeID
I use this sql query to calculate Total sale for Each Employee but how can i Caclulate is for Each Region.
Haven’t got access to Northwind right now, so this is untested, but you should get the idea…
There’s no need to get data about employees if all you want is sales per region. Your subquery is therefore redundant…
As discussed in the comments, this “double counts” sales where an employee is assigned to more than one region. In many cases, this is desired behaviour – if you want to know how well a region is doing, you need to know how many sales came from that region, and if an employee is assigned to more than one region, that doesn’t affect the region’s performance.
However, it means you overstate the sales if you add up all the regions.
There are two strategies to avoid this. One is to assign the sale to just one region; in the comments, you say there’s no data on which to make that decision, so you could do it on the “lowest regionID) – something like:
(again, no access to DB, so can’t test – but this should filter out duplicates).
Alternatively, you can assign a proportion of the sale to each region – though then rounding may cause the totals not to add up properly. That’s a query I’d like to try before posting though!