跨多个表的SQL条件求和

时间:2013-02-09 07:54:22

标签: mysql sql count sum

我有以下三个表

1。产品大师(下午)

  • Product_Code
  • PRODUCT_NAME
  • Product_Category(书籍, 文具,期刊,杂志)

2。订购大师(om)

  • Order_ID上
  • Order_No
  • ORDER_DATE

第3。订单行(ol)

  • Order_Line_ID
  • Order_ID上
  • PRODUCT_CODE
  • 数量
  • 金额

现在我需要记录集中的以下列:

  

om.order_no,om.order_date,sum(ol.qty)for Books,sum(ol.amount)for Books,sum(ol.qty)for Stationary,sum(ol.amount)for Stationary,sum(ol .qty)用于期刊,sum(ol.amount)用于期刊,sum(ol.qty)用于杂志,sum(ol.amount)用于杂志。

请帮助写条件金额。感谢。

1 个答案:

答案 0 :(得分:0)

尝试一下,

SELECT  a.Order_NO,
        a.Order_Date,
        SUM(CASE WHEN c.Product_Category = 'Books' THEN b.Qty ELSE 0 END) totalBooks,
        SUM(CASE WHEN c.Product_Category = 'Books' THEN b.Amount ELSE 0 END) totalBooks_Amount,
        SUM(CASE WHEN c.Product_Category = 'Stationary' THEN b.Qty ELSE 0 END) totalStationary,
        SUM(CASE WHEN c.Product_Category = 'Stationary' THEN b.Qty ELSE 0 END) totalStationary_Amount,
        SUM(CASE WHEN c.Product_Category = 'Journals' THEN b.Qty ELSE 0 END) totalJournals,
        SUM(CASE WHEN c.Product_Category = 'Journals' THEN b.Qty ELSE 0 END) totalJournals_Amount,
        SUM(CASE WHEN c.Product_Category = 'Magazines' THEN b.Qty ELSE 0 END) totalMagazines,
        SUM(CASE WHEN c.Product_Category = 'Magazines' THEN b.Qty ELSE 0 END) totalMagazines_Amount
FROM    OrderMaster a
        INNER JOIN OrderLines b 
            ON a.Order_ID = b.Order_ID
        INNER JOIN ProductMaster c
            ON b.Product_Code = c.Product_Code
GROUP   BY a.Order_NO, a.Order_Date