我有这个问题:
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)行的紫色颜色一样进行GROUP,我想添加所有(itempurchase_quantity)制作对(status_code)行的引用然后应用这个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
更新 这是一张详细说明我需要的照片:
答案 0 :(得分: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
答案 1 :(得分: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;
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;