如何在子查询中为特定ID求和?

时间:2019-04-28 14:18:22

标签: sql sum id

我对如何计算每个地区的总销售额感到迷惑。我已经尝试了一切。

我尝试在子查询中求和,但是之后就无法求和

SELECT   Region.RegionDescription, sq1.[Total sales]
FROM [Order Details]od
INNER JOIN
(SELECT OrderID, SUM(UnitPrice*Quantity)AS [Total sales]
FROM [Order Details]
Group By OrderID)sq1 ON sq1.OrderID=od.OrderID
INNER JOIN
Orders ON od.OrderID = Orders.OrderID 
INNER JOIN
Employees ON Employees.EmployeeID=Orders.EmployeeID
INNER JOIN
EmployeeTerritories ON 
Employees.EmployeeID=EmployeeTerritories.EmployeeID
INNER JOIN
Territories ON Territories.TerritoryID = 
EmployeeTerritories.TerritoryID
INNER JOIN
Region ON Region.RegionID = Territories.RegionID
GROUP BY  Region.RegionDescription, sq1.[Total sales]

我希望看到每个地区的销售总额

1 个答案:

答案 0 :(得分:0)

您可以做两件事。

删除子查询

SELECT r.RegionDescription, SUM(od.UnitPrice * od.Quantity)
FROM [Order Details] od
INNER JOIN Orders o ON od.OrderID = o.OrderID
INNER JOIN Employees e ON e.EmployeeID=o.EmployeeID
INNER JOIN EmployeeTerritories et ON e.EmployeeID=et.EmployeeID
INNER JOIN Territories t ON t.TerritoryID = et.TerritoryID
INNER JOIN Region r ON r.RegionID = t.RegionID
GROUP BY r.RegionDescription

保留子查询

SELECT r.RegionDescription, sum(sq1.[Total sales])
FROM (
    SELECT OrderID, SUM(UnitPrice*Quantity)AS [Total sales]
    FROM [Order Details]
    Group By OrderID
) sq1 ON sq1.OrderID=od.OrderID
INNER JOIN Orders o ON od.OrderID = o.OrderID 
INNER JOIN Employees e ON e.EmployeeID=o.EmployeeID
INNER JOIN EmployeeTerritories et ON e.EmployeeID=et.EmployeeID
INNER JOIN Territories t ON t.TerritoryID = et.TerritoryID
INNER JOIN Region r ON r.RegionID = t.RegionID
GROUP BY r.RegionDescription

第一个将明细记录与其余表联系起来。第二个摘要将详细信息汇总到订单级别,然后将其与其余表合并。我希望性能会相似。您将必须检查一下自己的运行速度。