我对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.ProductPrice
为OrderDetails.ProductCode
时尝试获取XXX
的和,并将其添加到Orders.Total
以获取总金额每个月/每年。
查询正在工作,除了一个问题(可能是业余错误或已经多次处理过)。执行LEFT JOIN
时,OrderDetails
表可以有多个链接到Orders
表的记录,这些记录会在SUM(Orders.Total)
中产生错误结果。我已经隔离了这个问题,我似乎无法解决它。
有人能指出我正确的方向吗?
答案 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);