mysql查询A表type字段等于1的num字段合计值和type字段等于2的num字段合计值,
一:使用IF函数 IF(Condition,A,B)
当condition为true时,返回A,否则返回B

sql语句:

select sum(if(type=1,num,0)) as total_1,sum(if(type=2,num,0)) as total_2 from a ;

二:使用case when

语句格式1:CASE WHEN condition THEN [A] ELSE [B]END
语句格式2:CASE condition WHEN value THEN [A] ELSE [B]END
当condition成立时,执行,否则执行B

sql语句:

select sum(CASE WHEN type=1 THEN num ELSE 0 END) as total_1,sum(CASE WHEN type=2 THEN num ELSE 0 END) as total_2 from a ;

或者

select sum(CASE type WHEN 1 THEN num ELSE 0 END) as total_1,sum(CASE type WHEN 2 THEN num ELSE 0 END) as total_2 from a ;

查看原帖

Last modification:October 18th, 2019 at 02:12 pm
如果觉得我的文章对你有用,请随意赞赏