分类汇总统计mysql数据库一个字段中不同的记录的总和

 

方法1、用 if 语句,如下例。
方法2、用case when then else 语句,用法如同if.

mysql> select sum(if(id<500,1,0)),sum(if(id>=500 && id<1000,1,0)) from customer;
 
+---------------------+---------------------------------+
| sum(if(id<500,1,0)) | sum(if(id>=500 && id<1000,1,0)) |
+---------------------+---------------------------------+
| 4                   | 204                             |
+---------------------+---------------------------------+
1 row in set

mysql> select sum(if(id<500,1,0)) as A,sum(if(id>=500 && id<1000,1,0)) as B from customer; 
+---+-----+
| A | B   |
+---+-----+
| 4 | 204 |
+---+-----+
1 row in set
posted @ 2017-12-07 11:57  EzrealR  阅读(6759)  评论(0编辑  收藏  举报