左连接返回错误值

时间:2014-12-12 01:24:54

标签: sql select sql-server-2005 group-by left-join

我对SQL查询不是很了解,但我试着写这个:

SELECT DATEPART(YY,Orders.OrderDate) as Year,
DATEPART(MM,Orders.OrderDate) as Month,
(SUM(case when OrderDetails.ProductCode = 'XXX' then 
OrderDetails.ProductPrice else 0 end) + SUM(Orders.Total))
AS XXX 
FROM Orders 
LEFT JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID 
WHERE Orders.OrderStatus = 'Shipped' 
GROUP BY DATEPART(MM,Orders.OrderDate), DATEPART(YY,Orders.OrderDate) 
ORDER BY DATEPART(YY,Orders.OrderDate),DATEPART(MM,Orders.OrderDate)

OrderDetails通过字段Orders链接到OrderID表。在此SELECT查询中,我在OrderDetails.ProductPriceOrderDetails.ProductCode时尝试获取XXX的和,并将其添加到Orders.Total以获取总金额每个月/每年。

查询正在工作,除了一个问题(可能是业余错误或已经多次处理过)。执行LEFT JOIN时,OrderDetails表可以有多个链接到Orders表的记录,这些记录会在SUM(Orders.Total)中产生错误结果。我已经隔离了这个问题,我似乎无法解决它。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

如果我们假设XXX产品每个订单最多只出现一次,那么这应该有效:

SELECT year(o.OrderDate) as Year, month(o.OrderDate) as Month,
       (COALESCE(SUM(od.ProductPrice), 0) + SUM(o.Total)) AS XXX 
FROM Orders o LEFT JOIN
     OrderDetails od
     ON o.OrderID = od.OrderID AND od.ProductCode = 'XXX'
WHERE o.OrderStatus = 'Shipped' 
GROUP BY year(o.OrderDate), month(o.OrderDate) 
ORDER BY year(o.OrderDate), month(o.OrderDate);

如果它可以多次出现,则将聚合的该部分移动到子查询:

SELECT year(o.OrderDate) as Year, month(o.OrderDate) as Month,
       (COALESCE(XXX, 0) + SUM(o.Total)) AS XXX 
FROM Orders o LEFT JOIN
     (SELECT od.OrderId, SUM(od.ProductPrice) as XXX
      FROM OrderDetails od
      WHERE od.ProductCode = 'XXX'
      GROUP BY od.OrderId
     ) od
     ON o.OrderID = od.OrderID 
WHERE o.OrderStatus = 'Shipped' 
GROUP BY year(o.OrderDate), month(o.OrderDate) 
ORDER BY year(o.OrderDate), month(o.OrderDate);