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判断,效率比较低下。

posted on 2013-03-21 22:09  andydaopeng  阅读(1526)  评论(0编辑  收藏  举报

导航