sql case用法举例

用一条sql语句查出学生表成绩小于60为不及格60-80为良好80-90为优秀

select name,
case when 成绩<60 then 不及格 when 成绩>=60 and 成绩<80 then 良好 when 成绩>=0 and 成绩<90 then 优秀 end as 成绩情况 
from 表名

 如是需要查询人数:

①:

select sum(if(score<60 , 1,0)) as '<60',sum(if(score between 60 and 80,1,0)) as '60~80',sum(if(score >80,1,0)) as '>80' from students;

②:

select if(score<60,'<60',if(score between 60 and 80,'60~80','>80')) as rang,count(*) from students group by  if(score<60,'<60',if(score between 60 and 80,'60~80','>80'));

③:

select score,count(*)   from students group by case  when score<60 then '<60' when  score between 60 and 80 then '60~80' else '>80' end;

 

posted @ 2017-08-28 20:04  向前爬的蜗牛  阅读(1544)  评论(0编辑  收藏  举报