Recently, I am working on a statistical function, which includes statistics based on the different states of a field in a table. When outputting, multiple data of the same business are aggregated into one piece of data for display.
The database is MYSQL, directly on the code, the example is as follows:
Create table statement:
CREATE TABLE `TB_TABLE` ( `ID` char(32) NOT NULL COMMENT '主键', `BIZ_NUM` varchar(30) DEFAULT NULL COMMENT 'Business Number', `BIZ_AMT` int(11) DEFAULT NULL COMMENT 'Amount', `TYPE` char(11) DEFAULT NULL COMMENT 'Type, 01-inflow; 02-outflow', PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Information table'; 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');
Expected output effect:
Business ID Inflow Amount Outflow Amount
111 150 80
222 70 50
method one:
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
Method Two:
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;