《SQL面试50题》刷题笔记 day15( 知识点:时间函数)

tonight 打工狗持续加班加满了。。

问题42 查询各学生的年龄 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

方法1

select sbirth, 
(DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(sbirth, '%Y')-
	(case when DATE_FORMAT(NOW(),'%m%d')>DATE_FORMAT(sbirth,'%m%d') 
	then 0 else 1 end)
	) as ageeee  
from student;

方法2

select sbirth, year(NOW())- year(sbirth)-
(case when (month(now())>= month(sbirth) and day(now())>= day(sbirth)) then 0 else 1 end) as agee
from student;

方法3

select s.sname, s.sbirth,
timestampdiff(year, s.sbirth, current_date()) as aggee, from student s;

通过此题学习了date_format()函数,以及函数timestampdiff()、函数timediff()、函数datediff()的区别。diff函数解法简单。

问题43 查询本周过生日的学生

Select * from student where week(sbirth) =week(now());

问题44 查询下周过生日的学生

select * from student where week(sbirth) =week(now())+1;

如果要查询上周,在跨年的情况下,这使得week()-1是0,而不是上一年的最后一周。
https://blog.csdn.net/Return_KB/article/details/78952426

更严谨的做法如下:

select * 
from Student 
where right(Yearweek(sbirth,0),2) = right(yearweek(date_add(now(), interval 7 day),0),2);
#为0,周天开始
select * 
from Student 
where right(Yearweek(sbirth,1),2) = right(yearweek(date_add(now(), interval 7 day),1),2);
#为1,周一开始

在2021年7月25日(周日)查询下周过生日的人时候,如果采用0,则可以找到
在这里插入图片描述
如果采用1,则为从周一开始数每周的第一天,则不能找到04号学生,这个学生的生日就变成了下下周。

其中,yearweek(date,mode)中的mode,其实week函数的mode也是这样定义的,都默认为0。
在这里插入图片描述

问题45 查询本月过生日的学生

select * from student where month(sbirth) =month(now());

问题46 查询下月过生日的学生

Select * from student where month(sbirth) =month(now())+1;
#若跨年则用如下查询:
select * 
from Student 
where (case when month(CURDATE())=12 
	   then 1 
	   else month(CURDATE())+1 
	   end) 
	   = month(sbirth);

这里下周上周、下月上月涉及都 跨年查询的问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值