【发布时间】:2013-07-29 14:00:19
【问题描述】:
我如何计算SQL ServerNorthwind数据库中每个地区的总销售额?
我已经运行了以下查询:
1)
select sum( od.Quantity * od.UnitPrice ), v.rid from
Orders o , [Order Details] od , (select et.EmployeeID eid, r.RegionID rid from region r, territories t , EmployeeTerritories et
where r.RegionID = t.RegionID and et.TerritoryID = t.TerritoryID ) v
where od.OrderID = o.OrderID and v.eid = o.EmployeeID
group by v.rid;
2)
select sum(b) from
(select sum(aa.UnitPrice * aa.Quantity) b
from region r, territories t , EmployeeTerritories et ,
(select o.EmployeeID , od.Quantity , od.UnitPrice from
Orders o , [Order Details] od
where od.OrderID = o.OrderID ) aa
where
t.regionid = r.regionid and
et.TerritoryID = t.TerritoryID and
et.EmployeeID = aa.EmployeeID
group by r.RegionID) x;
3)
select sum (Quantity * UnitPrice) from [Order Details];
如果您运行这些查询,您会发现第三个总和不等于第一个!说明我们每个地区都有一些重复记录!
【问题讨论】:
-
使用内连接避免重复
标签: sql sql-server northwind