查看2年之间售出的商品数量

时间:2020-05-12 20:58:41

标签: sql

我正在尝试查看2个不同年份之间每种产品的销售额。我已经为此困扰了几个小时,而我却不知所措。这是我当前的代码

SELECT DISTINCT od.ProductID, SUM(
CASE 
WHEN o.OrderDate between '2016-01-01' and '2016-12-31' THEN od.UnitPrice * od.Quantity 
WHEN o.OrderDate between '2017-01-01' and '2017-12-31' THEN od.UnitPrice * od.Quantity
) as '# of Units Sold' 
FROM OrderDetails od
Inner Join Orders o on od.OrderID = o.OrderID
GROUP BY od.ProductID
ORDER BY od.ProductID ASC;

当我运行它时,由于这种情况的语法不正确,我得到了一个错误。

我希望得到这样的输出:

Product ID | Units Sold in 2016 | Units Sold in 2017
    1               100                 200
    2                50                  75

请帮助??

1 个答案:

答案 0 :(得分:2)

您接近:

SELECT od.ProductID,
       SUM(CASE WHEN o.OrderDate between '2016-01-01' and '2016-12-31' THEN od.UnitPrice * od.Quantity
           END) as total_2016,
       SUM(CASE WHEN o.OrderDate between '2017-01-01' and '2017-12-31' THEN od.UnitPrice * od.Quantity
           END) as total_2017
FROM OrderDetails od JOIN
     Orders o 
     ON od.OrderID = o.OrderID
GROUP BY od.ProductID
ORDER BY od.ProductID ASC;

您需要两个单独的CASE表达式,每年一个。