2016-04-08 6 views
1

Ich habe unten TabellendatenMysql Bestandsberechnung Abfrage

Product Reason Qty 
Pepsi IN  10 
Pepsi Out 2 
Pepsi In  15 
Pepsi Out 5 
Coke IN  100 
Coke Out 20 
Coke In  35 
Coke Out 25 
Fanta Out  55 

und ich möchte wie unten führen zu bekommen:

Product Qty 
Pepsi 18 
Coke 90 
Fanta -55 

Ich habe unten Abfrage geschrieben, aber ich bin nicht in Fanta Ausgabe bekommen.

select indata.Name,indata.PRODUCTS_ID, (indata.QTY - outdata.QTY) as `QTY` from 
(
(select 
    distinct 
    stock.PRODUCTS_ID, 
    stock.Name, 
    stock.QTY 
    from stock where reason in ('IN','REFUND') 
    ) indata, 
(select 
    distinct 
    stock.PRODUCTS_ID, 
    stock.Name, 
    stock.QTY 
    from stock where reason in ('OUT','WASTE') 
) outdata 
); 

Antwort

2

Es sieht aus wie ein guter Kandidat für die bedingte Aggregation:

SELECT Product, 
     SUM(CASE WHEN reason IN ('IN','REFUND') THEN Qty 
       WHEN reason IN ('OUT','WASTE') THEN -Qty 
       ELSE NULL END) AS Qty 
FROM stock 
GROUP BY Product; 

LiveDemo

+1

wow !! Perfekt danke –