我有一个mysql客户表:
customer_id | customer_name | creation_date
1 | john | 2013-09-12 18:34:00
2 | banjo | 2013-01-11 14:34:00
我要实现的是知道下个月当前ot中与creation_date字段匹配的最近的DAY。
I.E如果当前日期是2014-01-20,我希望得到以下结果
customer_id | customer_name | creation_date | next_date
1 | john | 2013-09-12 18:34:00 | 2014-02-12
2 | banjo | 2013-01-11 14:34:00 | 2014-02-11
答案 0 :(得分:1)
以下似乎可行但未针对边缘情况进行测试:
SELECT
CURRENT_DATE AS cutoff_date,
date_column AS creation_date,
CASE
WHEN STR_TO_DATE(CONCAT_WS('-', YEAR(CURRENT_DATE), MONTH(CURRENT_DATE), DAY(date_column)), '%Y-%c-%e') >= CURRENT_DATE
THEN STR_TO_DATE(CONCAT_WS('-', YEAR(CURRENT_DATE), MONTH(CURRENT_DATE), DAY(date_column)), '%Y-%c-%e')
ELSE STR_TO_DATE(CONCAT_WS('-', YEAR(CURRENT_DATE), MONTH(CURRENT_DATE), DAY(date_column)), '%Y-%c-%e') + INTERVAL 1 MONTH
END AS next_date
FROM dates2
结果:
cutoff_date creation_date next_date
------------------- ------------------- -------------------
2014-01-20 00:00:00 2010-01-01 00:41:00 2014-02-01 00:00:00
2014-01-20 00:00:00 2010-01-10 00:06:00 2014-02-10 00:00:00
2014-01-20 00:00:00 2010-01-19 22:34:00 2014-02-19 00:00:00
2014-01-20 00:00:00 2010-01-19 23:13:00 2014-02-19 00:00:00
2014-01-20 00:00:00 2010-01-20 00:36:00 2014-01-20 00:00:00
2014-01-20 00:00:00 2010-01-20 00:43:00 2014-01-20 00:00:00
2014-01-20 00:00:00 2010-02-15 08:05:00 2014-02-15 00:00:00
2014-01-20 00:00:00 2010-02-25 22:50:00 2014-01-25 00:00:00
答案 1 :(得分:0)
首先计算想要的日期,然后使用min / max来获得最接近的日期。也许是这样的:
-- If your stored date is always in year 2013
select CASE WHEN DATE_ADD(DATE_ADD(creation_date, INTERVAL 1 YEAR), INTERVAL 1 MONTH) < SYSDATE
THEN DATE_ADD(creation_date, INTERVAL 1 YEAR)
ELSE DATE_ADD(DATE_ADD(creation_date, INTERVAL 1 YEAR), INTERVAL 1 MONTH)
END AS next_date
from customers;
这会使您的creation_date 2013-09-12
变为2014-10-12
。但是,如果你只想要这一天,这可能有用吗?:
-- If your stored date is always in year 2013
select str_to_date(concat(date_format(curdate(),'%Y-%m'), date_format(creation_date,'%d')),'%Y-%m-%d') as next_date
from customers;
这应该使用当前年份和月份,但只更改当天。您可以使用CASE
检查当前或下个月之间的差异是否更接近。
答案 2 :(得分:0)
你可以尝试这个,在mysql中你可以使用interval作为perticuler增量日期,如:
select customer_id,customer_name,creation_date,(creation_date+interval 1 year) as next_date from customer_info;
如果你愿意,