Mysql股票计算查询

时间:2016-04-08 17:47:04

标签: mysql

我有以下表数据

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

我希望得到如下结果:

Product Qty
Pepsi   18
Coke    90
Fanta   -55

我写了下面的查询,但我没有收到Fanta的输出。

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
);

1 个答案:

答案 0 :(得分:2)

它似乎是条件聚合的一个很好的候选者:

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