要理解它,请考虑“学生”表中的数据,如下所示 -
mysql> select * from students;+----+-----------+-----------+----------+----------------+| id | name | country | language | course |+----+-----------+-----------+----------+----------------+| 1 | francis | uk | english | literature || 2 | rick | usa | english | history || 3 | correy | usa | english | computers || 4 | shane | france | french | computers || 5 | validimir | russia | russian | computers || 6 | steve | australia | english | geoinformatics || 7 | rahul | india | hindi | yoga || 8 | harshit | india | hindi | computers || 9 | harry | nz | english | electronics |+----+-----------+-----------+----------+----------------+9 rows in set (0.00 sec)
现在,假设我们想知道有多少学生属于美国、英国、新西兰、印度、俄罗斯、法国等,那么我们可以在 case 语句中使用“国家/地区”列,如下所示-
mysql> select sum(case when country = 'usa' then 1 else 0 end) as usa,-> sum(case when country = 'uk' then 1 else 0 end) as uk,-> sum(case when country = 'india' then 1 else 0 end) as india,-> sum(case when country = 'russia' then 1 else 0 end) as russia,-> sum(case when country = 'france' then 1 else 0 end) as france,-> sum(case when country = 'nz' then 1 else 0 end) as nz,-> sum(case when country = 'australia' then 1 else 0 end) as australia-> from students;+------+------+-------+--------+--------+------+-----------+| usa | uk | india | russia | france | nz | australia |+------+------+-------+--------+--------+------+-----------+| 2 | 1 | 2 | 1 | 1 | 1 | 1 |+------+------+-------+--------+--------+------+-----------+1 row in set (0.07 sec)
以上就是如何在 mysql case 语句中使用列数据?的详细内容。