企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# mysql 查询一张表中某个字段不同状态的数量统计 最近统计数据的时候有这样的业务需求,统计一张表里面一个字段不同的类型值数量多少,不可能每个类型值都写一遍语句吧! ![![](https://img.kancloud.cn/11/c5/11c551294801bf07ec32d448c048ed30_1194x579.png)](images/screenshot_1641798543853.png) 其中 origin 是用户来源,其中的值有 iPhone 、Android 、Web 三种,现在需要分别统计由这三种渠道注册的用户数量。 **解决方案1** ~~~ SELECT count(*) FROM user_operation_log WHERE origin = 'iPhone'; SELECT count(*) FROM user_operation_log WHERE origin = 'Android'; SELECT count(*) FROM user_operation_log WHERE origin = 'Web'; ~~~ 用 where 语句分别统计各自的数量。 这样查询的量有点多了,如果这个值有 10 个呢,那还得写 10 条相似的语句,很麻烦。 有没有一条语句就搞定的呢?于是去查了些资料。 **解决方案2** 我们知道 count 不仅可以用来统计行数,也能统计列值的数量,例如: 统计 user_operation_log 有多少行: `SELECT count(*) FROM user_operation_log` 统计 origin 这列值不为 NULL 的数量: ``` SELECT count(origin) FROM user_operation_log ``` 所以我们可以利用这个特性来实现上面的需求 **第一种写法(用 count 实现)** ``` SELECT count(origin = 'iPhone' OR NULL) AS iPhone, count(origin = 'Android' OR NULL) AS Android, count(origin = 'Web' OR NULL) AS Web FROM user_operation_log; ``` 查询结果 ![](https://img.jbzj.com/file_images/article/201704/2017428141215359.png?2017328141225) **第二种写法(用 sum 实现)** ``` SELECT sum(if(origin = 'iPhone', 1, 0)) AS iPhone, sum(if(origin = 'Android', 1, 0)) AS Android, sum(if(origin = 'Web', 1, 0)) AS Web FROM user_operation_log; ``` 查询结果 ![](https://img.jbzj.com/file_images/article/201704/2017428141215359.png?2017328141225) **第三种写法(改写 sum)** ~~~ SELECT sum(origin = 'iPhone') AS iPhone, sum(origin = 'Android') AS Android, sum(origin = 'Web') AS Web FROM user_operation_log; ~~~ 查询结果 ![](https://img.jbzj.com/file_images/article/201704/2017428141215359.png?2017328141225) **第四种写法(来自掘金用户 杰夫 的答案)** ``` SELECT origin,count(*) num FROM user_operation_log GROUP BY origin; ``` 查询结果 ![](https://img.jbzj.com/file_images/article/201704/2017428141350746.png?2017328141358) 至此,已经达到了我们的需求。 我用了解决方案2里面的第一种和第三种 转载:https://www.jb51.net/article/112492.htm ··· SELECT * FROM test; SELECT *, sum(type = 1) AS type1, sum(type = 0) AS type0 FROM test GROUP BY no; SELECT *, count(type = 1 OR NULL) AS type1, count(type = 0 OR NULL) AS type0 FROM test GROUP BY no; SELECT *, sum(if(type = 1,1,0)) AS type1, sum(if(type = 0,1,0)) AS type0 FROM test GROUP BY no; ![](https://img.kancloud.cn/0b/24/0b248772d726e0788b5ed3919e044a4a_340x184.png) ![](https://img.kancloud.cn/3c/4a/3c4a5a054c6a571d2462f73bf3696f83_381x106.png)