在mysql当中,怎么计算两个日期的“年差”,差了多少年?
TimeStampDiff(间隔类型,前一个日期,后一个日期)
例如距离现在差了多少年:TimeStampDiff(year, 前一个日期, now())
间隔类型有:second秒,minute分,hour时,day天,week周,month月,quarter季度,year年。
例题1:给任职日期超过30年的员工加薪10%。
思路:update emp set sal=sal*1.1 where 任职日期 > 30年。
update emp
set sal = sal * 1.1
where timestampdiff(year, hiredate, now()) > 30;
例题2:列出在每个部门工作的员工数量,平均工资,平均服务期限。
思路:使用外连接。
select d.deptno, count(e.ename) ‘人数’, ifnull(avg(e.sal), 0) ‘平均月薪’, ifnull(avg(timestampdiff(year, e.hiredate, now())), 0) ‘平均服务年数’
from emp e
right join dept d
on e.deptno = d.deptno
group by d.deptno;