SQLServer 的case when語句使用實現統計
阿新 • • 發佈:2018-06-08
wid eat spa height 希望 case bsp win 數據
已知有表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 0
end
另一種用法是
case when result_info =‘win‘ then 1
else 0
end
case when 語句在判斷性別時也是常用的
如在數據庫中性別在表中存的是數字1、2,但是希望查詢出來男、女
select (case gender when 1 then ‘男’
when 2 then ‘女‘
else ‘其他’
end) as gender from Table1;
SQLServer 的case when語句使用實現統計