select name,datediff(cuidate(),entrydate) as 'entrydays' from emp order by entrydays desc;
5.流程(控制)函数
可以在SQL语句中实现条件筛选,从而提高语句的效率
函数
功能
if(value,t,f)
如果value为true,则返回t,否则返回f
ifnull(value1,value2)
如果value1不为空,返回value1.否则返回value2
case when [val1] then [res1] …else[default] end
如果val1为true,返回res1,…否则返回default默认值
case [expr] when [val1] then [res1]…else [default] end
如果expr的值等于val1,返回res1,…否则返回default默认值
案例
统计班级各个学员的成绩,展示的规则如下:
大于等于85,展示优秀
大于等于65,展示及格
否则,展示不及格
1 2 3 4 5 6 7 8
create table score( id int comment 'ID', name varchar(20) comment '姓名' math int comment '数学' english int comment '英语' chinese int comment '语文' )comment '学员成绩表'; insert into score(id,name,math,english,chinese) values (1,'Tom',67,88,95),(2,'Rose',23,66,98),(3,'Jack',54,98,76)
先展示分数—等级
1 2 3 4 5 6 7
select id, name, (case when math >= 85 then'优秀’when math >=60 then'及格'else'不及格'end )'数学', (case when english >= 85 then'优秀’when english >=60 then'及格'else'不及格'end )'英语', (case when chinese >= 85 then'优秀’when chinese >=60 then'及格’else'不及格'end )'语文' from scoer