MYSQL
专栏收录该内容
145 篇文章6 订阅
建表语句:
CREATE TABLE TB_TABLE (
ID char(32) NOT NULL COMMENT ‘主键’,
BIZ_NUM varchar(30) DEFAULT NULL COMMENT ‘业务编号’,
BIZ_AMT int(11) DEFAULT NULL COMMENT ‘金额’,
TYPE char(11) DEFAULT NULL COMMENT ‘类型,01-流入;02-流出’,
PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘信息表’;
INSERT INTO TB_TABLE VALUES(‘1’,‘111’,120,‘01’);
INSERT INTO TB_TABLE VALUES(‘2’,‘111’,80,‘02’);
INSERT INTO TB_TABLE VALUES(‘3’,‘111’,30,‘01’);
INSERT INTO TB_TABLE VALUES(‘4’,‘222’,70,‘01’);
INSERT INTO TB_TABLE VALUES(‘5’,‘222’,50,‘02’);
预期输出效果:
业务编号 流入金额 流出金额
111 150 80
222 70 50
方法一:
select
t.biz_num,
sum(case when t.type=‘01’ then t.biz_amt end) as bizAmtIn,
sum(case when t.type=‘02’ then t.biz_amt end) as bizAmtOut
from tb_table t
where t.type in (‘01’,‘02’)
group by t.biz_num
方法二:
select
t.biz_num,
sum(if(t.type=‘01’,t.biz_amt,0)) as bizAmtIn,
sum(if(t.type=‘02’,t.biz_amt,0)) as bizAmtOut
from tb_table t
where t.type in (‘01’,‘02’)
group by t.biz_num;