我在MYSQL中有一个表,其列中的日期表示为字符串。
Example: 20190828 represents 28th Aug 2019
现在,我想获取该给定日期的下一个星期日,如果给定日期已经是星期日,则无需进行任何更改。还有如何获取给定日期的月底。
Example:
For input - 20190828, next sunday is 20190901, end of the month is 20190831
答案 0 :(得分:2)
您可以将字符串转换为日期,然后进行算术运算:
select
mydate,
str_to_date(mydate, '%Y%m%d') + interval 6 - weekday(str_to_date(mydate, '%Y%m%d')) day next_sunday
last_day(str_to_date(mydate, '%Y%m%d')) last_day_of_the_month
from mytable
实际上,甚至没有必要进行强制转换,因为MySQL应该在此处隐式将字符串转换为日期:
select
mydate,
mydate + interval 6 - weekday(mydate) day next_sunday,
last_day(mydate) last_day_of_the_month
from mytable
with mytable as (select '20190828' mydate union all select '20200327')
select
mydate,
mydate + interval 6 - weekday(mydate) day next_sunday,
last_day(mydate) last_day_of_the_month
from mytable
mydate | next_sunday | last_day_of_the_month :------- | :---------- | :-------------------- 20190828 | 2019-09-01 | 2019-08-31 20200327 | 2020-03-29 | 2020-03-31