MYSQL:SUM与多个组

时间:2014-09-03 02:35:55

标签: mysql sql

我有这样的表:

PRODUCTID      REORDER_QTY      TYPE      ADJUST_TYPE  
-------------  ---------------  --------  -----------------
         4343             2.00  Transfer  ADD              
         4730             2.00  Transfer  ADD              
         4730             2.00  Transfer  ADD              
         4730             1.00  Transfer  DEDUCT           
         3643            20.00  Transfer  ADD              
         3643             3.00  Transfer  DEDUCT           

如何通过 PRODUCTID 以及 ADJUST_TYPE 编写一个sql来累计 REORDER_QTY ,之后通过总和得到它的余额 ADD 并减去总和 DEDUCT

我想要的示例sql结果输出:

PRODUCTID        TYPE                   Total_Balance
-------------    ----------             ---------------
4730             Transfer               ((SUM the REORDER_QTY by ADD) - (SUM the REORDER_QTY by DEDUCT))
3643             Transfer               ((SUM the REORDER_QTY by ADD) - (SUM the  REORDER_QTY by DEDUCT))
4343             Transfer               ((SUM the REORDER_QTY by ADD) - (SUM the  REORDER_QTY by DEDUCT))

任何帮助都会很棒,谢谢

2 个答案:

答案 0 :(得分:1)

您只想要条件聚合:

select productid, type,
       sum(case when adjust_type = 'ADD' then reorder_qty
                when adjust_type = 'DEDUCT' then - reorder_qty
                else 0
           end) as total_balance
from atable
group by productid, type;

答案 1 :(得分:0)

因为这是mysql,所以你可以这样做:

select
    productid,
    sum((2 * (adjust_type = 'ADD') - 1) * reorder_qty) as total_balance
from mytable
group by productid

这是有效的,因为在mysql中,布尔条件为true生成1的结果,为false生成0,因此(2 * (adjust_type = 'ADD') - 1)1ADD生成-1,否则,使算术更简单。