mysql中的case when then 語句類似於其他編程中的if/else if/else。基本語法如下:
case
when...then...
when...then...
when...then...
else
end
比賽年份和結果表
create table scores
(
date_year int,
win_loss varchar(5)
);
數據
insert into scores
value
(2005,'loss'),(2006,'win'),(2007,'win'),(2008,'loss'),(2009,'loss'),(2010,'tie'),
(2005,'tie'),(2006,'win'),(2007,'loss'),(2008,'loss'),(2009,'win'),(2010,'tie');
輸出結果
select date_year,
case
when win_loss ='loss' then '輸'
when win_loss ='win' then '贏'
when win_loss ='tie' then '平'
end as result
from scores;
mysql> select date_year,
-> case
-> when win_loss ='loss' then '輸'
-> when win_loss ='win' then '贏'
-> when win_loss ='tie' then '平'
-> end as result
-> from scores;
+-----------+--------+
| date_year | result |
+-----------+--------+
| 2005 | 輸 |
| 2006 | 贏 |
| 2007 | 贏 |
| 2008 | 輸 |
| 2009 | 輸 |
| 2010 | 平 |
| 2005 | 平 |
| 2006 | 贏 |
| 2007 | 輸 |
| 2008 | 輸 |
| 2009 | 贏 |
| 2010 | 平 |
+-----------+--------+
12 rows in set (0.00 sec)
case when then 中使用聚合函數。
假如贏一場得3分,輸一場-1分,平一場0分。如何得到每年的積分。
select date_year,
sum(case
when win_loss ='loss' then -1
when win_loss ='win' then 3
when win_loss ='tie' then 0
end) all_score
from scores
group by date_year;
mysql> select date_year,
-> sum(case
-> when win_loss ='loss' then -1
-> when win_loss ='win' then 3
-> when win_loss ='tie' then 0
-> end) all_score
-> from scores
-> group by date_year;
+-----------+-----------+
| date_year | all_score |
+-----------+-----------+
| 2005 | -1 |
| 2006 | 6 |
| 2007 | 2 |
| 2008 | -2 |
| 2009 | 2 |
| 2010 | 0 |
+-----------+-----------+
6 rows in set (0.00 sec)