已知有表game_info 如下
date_info | result_info |
2018-2-4 | win |
2018-2-4 | lose |
2018-2-4 | win |
2018-2-4 | lose |
2018-2-5 | lose |
2018-2-5 | lose |
2018-2-5 | lose |
问如何查询得到如下结果?
date_info | win | lose |
2018-2-4 | 2 | 2 |
2018-2-5 | 0 | 3 |
首先创建表create table game_infdate_info not null,
result_info varchar(5) check(result_info in('win','lose'))); //插入数据 insert into game_info values('2018-2-4','win'),('2018-2-5','lose'); //查询语句 select date_info ,sum(case result_info when 'win' then 1 else 0 end) as win,sum( case result_info when 'lose' then 1 else 0 end) as lose from game_info group by date_info order by date_info asc;
这里要说明的是case when语句的使用,
case when 有两种用法
case result_info when 'win' then 1 else 0end
另一种用法是
case when result_info ='win' then 1 else 0end
case when 语句在判断性别时也是常用的
如在数据库中性别在表中存的是数字1、2,但是希望查询出来男、女
select (case gender when 1 then '男’ when 2 then '女' else ‘其他’ end) as gender from Table1;