id start_date interval period
1 1/22/2018 2 month
2 2/25/2018 3 week
3 11/24/2017 3 day
4 7/22/2017 1 year
5 2/25/2018 2 week
以上是我的表格数据示例。 start_dates 将根据时间间隔和期间到期(即 id-1 将在 start_date 2 个月后到期,id-2 将在 3 周后到期,反之亦然)。期间是(日、周、月、年)的枚举。客户可以提供任何日期。比方说 25-06-2026 到 13-07-2026 这样的。我必须返回截止日期在那个时期内的 ID。我希望我把我的问题说清楚了。
这是我为解决此问题所做的工作。我正在使用 MySQL 5.7。我找到了使用递归 CTE 实现此目的的方法。(在 mysql 5.7 中不可用)。有一种方法可以通过使用内联子查询和联合来填充虚拟记录来实现这一点,它是一个性能 killer ,并且对记录的数量有限制。(如链接 Generating a series of dates 中给出的那样)我已经达到了一个地步获取单个日期的结果非常容易。下面是我的查询(在 oracle 中)
select id
from (select a.*,
case
when period='week'
then mod((to_date('22-07-2018','dd-mm-yyyy')-start_date),7*interval)
when period='month' and to_char(to_date('22-07-2018','dd-mm-yyyy'),'dd')=to_char(start_date,'dd')
and mod(months_between(to_date('22-07-2018','dd-mm-yyyy'),start_date),interval)=0
then 0
when period='year' and to_char(to_date('22-07-2018','dd-mm-yyyy'),'dd-mm')=to_char(start_date,'dd-mm')
and mod(months_between(to_date('22-07-2018','dd-mm-yyyy'),start_date)/12,interval)=0
then 0
when period='day'
and mod((to_date('22-07-2018','dd-mm-yyyy')-start_date),interval)=0
then 0 else 1 end filter from kml_subs a)
where filter=0;
但我需要在一段时间内执行此操作,而不是单个日期。任何建议或解决方案将不胜感激。
谢谢, 看南
最佳答案
假设这是一个 Oracle 问题而不是 MySQL:
我认为您需要做的第一件事是计算截止日期。我认为一个简单的 case 语句可以为您解决这个问题:
case when period = 'day' then start_date + numtodsinterval(interval,period)
when period = 'week' then start_date + numtodsinterval(interval*7,'day')
when period = 'month' then add_months(start_date,interval)
when period = 'year' then add_months(start_date,interval*12)
end due_date
然后,使用新的 due_date 字段,您可以检查截止日期是否在之间<
所需的日期范围内。
select *
from(
select id,
start_date,
interval,
period,
case when period = 'day' then start_date + numtodsinterval(interval,period)
when period = 'week' then start_date + numtodsinterval(interval*7,'day')
when period = 'month' then add_months(start_date,interval)
when period = 'year' then add_months(start_date,interval*12)
else null end due_date
from data)
where due_date between date '2018-02-25' and date '2018-03-12'
上述 2/25/18 和 3/12/18 之间的查询检查使用您的数据生成以下输出:
+----+-------------+----------+--------+-------------+
| id | start_date | interval | period | due_date |
+----+-------------+----------+--------+-------------+
| 2 | 05-FEB-2018 | 3 | week | 26-FEB-2018 |
| 5 | 25-FEB-2018 | 2 | week | 11-MAR-2018 |
+----+-------------+----------+--------+-------------+
关于mysql - 根据给定的日期周期检查动态到期日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003756/