MySQL聚合函数如何与MySQL IF()函数结合?

WBOY
发布: 2023-08-27 13:37:13
转载
869 人浏览过

MySQL聚合函数如何与MySQL IF()函数结合?

Combining MySQL aggregate functions with MySQL IF() function can be very helpful to get the specific output we want. Consider the following queries which combine SUM() and COUNT() aggregate functions with IF() function.

Example

mysql> Select SUM(IF(Language = &#39;English&#39;, 1, 0)) As English, SUM(IF(Language <> &#39;English&#39;,1,0)) AS "Non-English" from Students;
+---------+-------------+
| English | Non-English |
+---------+-------------+
| 5       | 4           |
+---------+-------------+
1 row in set (0.00 sec)
登录后复制

上述查询将SUM()聚合函数与IF()函数结合使用,从“学生”表中获取英语母语学生和非英语母语学生的输出。

mysql> Select COUNT(IF(country = &#39;USA&#39;, 1, NULL))AS USA,
    -> COUNT(IF(country = &#39;UK&#39;, 1, NULL))AS UK,
    -> COUNT(IF(country = &#39;France&#39;, 1, NULL))AS France,
    -> COUNT(IF(country = &#39;Russia&#39;, 1, NULL))AS Russia,
    -> COUNT(IF(country = &#39;Australia&#39;, 1, NULL))AS Australia,
    -> COUNT(IF(country = &#39;INDIA&#39;, 1, NULL))AS INDIA,
    -> COUNT(IF(country = &#39;NZ&#39;, 1, NULL))AS NZ FROM Students;
+-----+----+--------+--------+-----------+-------+----+
| USA | UK | France | Russia | Australia | INDIA | NZ |
+-----+----+--------+--------+-----------+-------+----+
| 2   | 1  | 1      | 1      | 1         | 2     | 1  |
+-----+----+--------+--------+-----------+-------+----+
1 row in set (0.07 sec)
登录后复制

上面的查询将COUNT()聚合函数与IF()函数结合起来,以从“Students”表中获取国家数量的输出。

以上是MySQL聚合函数如何与MySQL IF()函数结合?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!