表结构
create table store
(
   id                   int not null auto_increment,
   tool                 varchar(50) comment '工具',
   type                 int comment '操作类型,有 入库 出库 
   number               int comment '数量',
   primary key (id)
);
表数据
--------------------------------------
id          tool             type     number    
01         台式机          入库        100
02         台式机          出库        50
03         笔记本          入库        300
04         笔记本          入库         200
05         笔记本          出库         400
-----------------------------------------------
想要的结果
tool                库存         
台式机            50
笔记本            100
-------------------------------------
库存=入库-出库
请问怎么用一条sql写出来

解决方案 »

  1.   

    select tool,sum(if(type='入库',number,-1*number)) as 库存
    from tt group by tool
      

  2.   

    select tool,sum(if(type='入库',number,-number)) as 库存
    From store
    group By tool
      

  3.   


    mysql> select tool,sum(case type when '入库' then number else -number end) from
    store group by tool //
      

  4.   

    select tool,sum(if(type='入库',number,-1*number)) as 库存
    from tt group by tool
    只有入是正数,其它的为负数