以学生的生日为2013-08-01格式为例
两种方法
substring()函数,用法为substring(str,n,m),表示将字符串str, 从第n位数开始,截取长度为m
substring(birthday,6,2)
? ?这样2013-08-01,变成了08,同时使用强制类型转换,将字符串变为整形,08 -> 8
? 考虑到月份在1-11的时候,可以直接对当前日期的所在月份加1,而当为12月时,则需要使其下一月为1,故使用if 转换
if(m2 < 12, m2 + 1, 1) as m2,
? 将学生的生日m2与当前日期的下一个月的月份比较,得到下一个月过生日的学生。
select
birthday,
m1,
m2
from
(
select
birthday,
if(m2 < 12, m2 + 1, 1) as m2,
m1
from
(
select
birthday,
month(`current_date`()) as m2,
-- 12 m2,
cast(substring(birthday,6,2) as int) m1
from Student
limit 100
)t1
)t2
where m1 = m2
last_day()函数是取日期的所在月份的最后一天,如2020-02-01的最后一日为2020-02-29,
Hive SQL用法为last_day(2020-02-01,1),而在一般sql中写法为last_day(2020-02-01,interval 1 days),略有不同
month(date_add(last_day(`current_date`()),1))
month(birthday) = 下一个月
day(birthday) >= day(`current_date`())
select
birthday
from Student
where month(birthday) = month(date_add(last_day(`current_date`()),1))
and day(birthday) >= day(`current_date`())
order by birthday