按数量对订单进行排序,甚至可以显示数量为0

时间:2016-02-23 09:34:22

标签: mysql sql

我已经写了这一点SQL:它返回了11月份销售的物品。但是,我想显示已售出的所有项目,只是为了在那个月没有销售的那个项目旁边加上0。 希望得到一些指导:

SELECT ItemID, SUM(Quantity)
FROM orderitems
WHERE OrderNumber IN(
    SELECT OrderNumber
    FROM `order`
    WHERE OrderDate > "2015-11-31") GROUP BY ItemID;

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT ItemID, 
       COALESCE(SUM(CASE 
                      WHEN o2.OrderDate > '2015-11-31' 
                      THEN Quantity 
                    END), 0) AS Sum_Of_Quantity 
FROM orderitems AS o1
LEFT JOIN (SELECT OrderNumber, OrderDate
           FROM `order`
           WHERE OrderDate > '2015-11-31') AS o2
   ON o1.OrderNumber = o2.OrderNumber
GROUP BY ItemID;

答案 1 :(得分:0)

这里还需要一个表:一个包含完整项目清单的表格,无论是否订购。

那就是:

SELECT
    FullListOfItemsOnSale.ItemID,
    IFNULL(OrdetedItems.Quantity, 0) AS Quantity
FROM FullListOfItemsOnSale
LEFT JOIN (
    SELECT ItemID, SUM(i.Quantity) AS Quantity
    FROM orderitems i
    INNER JOIN `order` o ON o.OrderNumber = i.OrderNumber
                        AND o.OrderDate > "2015-11-31"
) OrdetedItems ON OrdetedItems.ItemID = FullListOfItemsOnSale.ItemID

答案 2 :(得分:0)

SELECT ItemID, 
       ISNULL(SUM(CASE WHEN c2.OrderDate > '2015-11-31' THEN Quantity END), 0) Sum_Of_Quantity 
FROM orderitems AS o1
LEFT JOIN (SELECT OrderNumber, OrderDate
           FROM `order`
           WHERE OrderDate > '2015-11-31') AS o2
   ON o1.OrderNumber = o2.OrderNumber
GROUP BY ItemID;