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 = 'English', 1, 0)) As English, SUM(IF(Language <> 'English',1,0)) AS "Non-English" from Students; +---------+-------------+ | English | Non-English | +---------+-------------+ | 5 | 4 | +---------+-------------+ 1 row in set (0.00 sec)
登錄后復(fù)制
上述查詢將SUM()聚合函數(shù)與IF()函數(shù)結(jié)合使用,從“學(xué)生”表中獲取英語母語學(xué)生和非英語母語學(xué)生的輸出。
mysql> Select COUNT(IF(country = 'USA', 1, NULL))AS USA, -> COUNT(IF(country = 'UK', 1, NULL))AS UK, -> COUNT(IF(country = 'France', 1, NULL))AS France, -> COUNT(IF(country = 'Russia', 1, NULL))AS Russia, -> COUNT(IF(country = 'Australia', 1, NULL))AS Australia, -> COUNT(IF(country = 'INDIA', 1, NULL))AS INDIA, -> COUNT(IF(country = 'NZ', 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)
登錄后復(fù)制
上面的查詢將COUNT()聚合函數(shù)與IF()函數(shù)結(jié)合起來,以從“Students”表中獲取國家數(shù)量的輸出。
以上就是MySQL聚合函數(shù)如何與MySQL IF()函數(shù)結(jié)合?的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!