0

我有以下三个表

1.产品大师(下午)

  • 产品代码
  • 产品名称
  • Product_Category(书籍、文具、期刊、杂志)

2.订单大师(om)

  • Order_ID
  • 订单号
  • 订购日期

3.订单行(ol)

  • Order_Line_ID
  • Order_ID
  • 产品代码
  • 数量
  • 数量

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

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) 用于杂志。

请帮助编写条件总和。谢谢。

4

1 回答 1

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
于 2013-02-09T07:59:53.840 回答