MySQL聚合函數如何與MySQL IF()函式結合?

WBOY
發布: 2023-08-27 13:37:13
轉載
777 人瀏覽過

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學習者快速成長!