简体   繁体   English

基于可变开始日期 + 天数间隔,我需要找到当天之后的下一个日期

[英]Based on a Variable Start Date + Days Interval, I need to find the next date after the current day

I have an Anchor Date, eg.我有一个锚日期,例如。 01-01-2020, which is a variable. 01-01-2020,这是一个变量。 I also have a days interval, eg.我也有几天的间隔,例如。 7 days, which is also a variable. 7天,也是一个变数。 I need to get the next date on or after the current date which is a whole number of intervals after the anchor date.我需要在当前日期或之后获取下一个日期,这是锚定日期之后的整数个间隔。

It's 01-16-2020 right now.现在是 01-16-2020。 The date I would expect is 01-22-2020.我期望的日期是 01-22-2020。

The result date will be within a SELECT Statement as a column.结果日期将作为列在 SELECT 语句中。 The select statement provides the variables. select 语句提供变量。

Consider:考虑:

dateadd(
    day,
    7 - datediff(day, '2020-01-01', cast(getdate() as date)) % 7,
    cast(getdate() as date)
)

Where the anchor date is '2020-01-01' and 7 is the interval.其中锚定日期是'2020-01-01'7是间隔。

This works by taking the days difference between the current date and the anchor: for today 2020-01-16, result is 15. Then we get the modulo 7 of this value (which is 1), and substract it from 7 (gives 6), which gives us the number of days that we need to add to the current date to get the expected value (2020-01-22).这是通过获取当前日期和锚点之间的天数差异来工作的:对于今天 2020-01-16,结果是 15。然后我们得到这个值的模 7(即 1),并从 7 中减去它(给出 6 ),它为我们提供了需要添加到当前日期以获得预期值 (2020-01-22) 的天数。

Demo on DB Fiddle DB Fiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM