Mysql case when then 和sum联合使用

case when语法如下:

case condition when value1 then a 

when value2 then b

...

else c end '别名';

或者:

case when condition=value1 then a

when conditon=value2 then b

...

else c end '别名';

计算每个省的人的总年龄和男的总年龄:

select sum(age) as age_total , sum(case sex when 'male' then age else 0 end ) age_male_total  from people group by provice;

注意:若每个省份男的比较多,则此 sql语句要进行多次case判断,效率比较低下。

原文地址:https://www.cnblogs.com/andydao/p/2974426.html