1

我有这个查询:

SELECT (
        SELECT purchase_code 
        FROM qa_suppliers_invoices a 
        WHERE a.supplier_invoice_code = b.item_invoicecodesupplier
       ) AS purchase_code, 
      item_code, 
      status_code, 
      itempurchase_quantity, 
      item_costprice 
FROM qa_items_purchases b
ORDER BY purchase_code LIMIT 0,20000;

它返回以下数据 在此处输入图像描述

我想使用(item_code)行像紫色线一样进行分组,我想添加所有引用(status_code)行的(itempurchase_quantity),然后像图像一样应用这个ecuation(status_15 - status_16)。

我想要这个结果,GROUP():

purchase_code  item_code  status_code  itempurchase_quantity  item_costprice
1              1506       15           713                    126.94
2              1503       16           12                     0.00
2              1683       15           9                      25.28
2              1931       15           60                     0.00

在 item_code(1997) 不存在的情况下 status_code = 15 因此返回一个负数 (-9) 那么你不需要显示。

2              2325       16           50                     849.97

注意: 我需要消除所有 16 个 status_code

Demo data to play with query at sqlfiddle

更新: 这是一张详细说明我需要的图片: 在此处输入图像描述

4

2 回答 2

2
SELECT 
      a.purchase_code,
      b.item_code, 
      '15' AS status_code,
      SUM(
        CASE b.status_code 
            WHEN 15 THEN b.itempurchase_quantity
        ELSE 
            - (b.itempurchase_quantity) 
        END) 
        AS itempurchase_quantity,
      b.item_costprice
FROM qa_items_purchases b
    INNER JOIN qa_suppliers_invoices a 
        ON a.supplier_invoice_code = b.item_invoicecodesupplier
GROUP BY purchase_code, b.item_code, b.item_costprice
    HAVING itempurchase_quantity > 0
    ORDER BY purchase_code 
    LIMIT 0,20000
于 2012-07-21T07:46:04.173 回答
2

用这个

SELECT purchase_code, item_code, status_code, 
     SUM(case status_code 
         when 15 then itempurchase_quantity
         ELSE (-1*itempurchase_quantity) END
        ) AS itempurchase_quantity
FROM myTable
GROUP BY purchase_code;

演示

笔记

您将需要使用您的数据,而不是 myTable。我已经创建myTable了您在图像中显示的数据。

我认为新的查询将是

SELECT (
    SELECT purchase_code 
    FROM qa_suppliers_invoices a 
    WHERE a.supplier_invoice_code = b.item_invoicecodesupplier
   ) AS purchase_code, 
  item_code, 
  status_code, 
  SUM(case status_code 
         when 15 then itempurchase_quantity
         ELSE (-1*itempurchase_quantity) END
        ) AS itempurchase_quantity, 
  item_costprice 
FROM qa_items_purchases b
GROUP BY purchase_code
ORDER BY purchase_code 
LIMIT 0,20000;

更新 1

SELECT purchase_code, item_code, status_code, 
       SUM(case status_code 
           when 15 then itempurchase_quantity
           ELSE (-1*itempurchase_quantity) END
          ) AS itempurchase_quantity
FROM myTable
GROUP BY purchase_code, item_code;

新演示

于 2012-07-21T07:54:31.733 回答