方法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
.....
方法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
转载请注明:谷谷点程序 » 分类汇总统计mysql数据库一个字段中不同的记录的总和