现在的位置: 首页 > 综合 > 正文

分类统计

2018年02月04日 ⁄ 综合 ⁄ 共 659字 ⁄ 字号 评论关闭

表结构
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
-----------------------------------------------
想要的结果
工具 库存  

---------------------------------------------
台式机 50
笔记本 100
-------------------------------------
库存=入库-出库

 

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

     说明:流程控制 if(exp1,exp2,exp3)

     如果表达式exp1成了就执行exp2,不成立就执行exp3;

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

抱歉!评论已关闭.