将MySQL聚合函数与MySQLIF()
函数结合起来对获得我们想要的特定输出非常有帮助。请看以下查询,这些查询将功能与功能结合SUM()
和COUNT()
聚合IF()
。
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)
上面的查询将SUM()
聚合函数与IF()
函数结合起来,以从“学生”表中获取英语学生和非英语学生的输出。
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)
上面的查询将COUNT()
聚合函数与IF()
函数结合在一起,以从“学生”表中获取多个国家/地区的输出。