sql - 根据间隔(月/季)查找下一个日期
问题描述
CREATE TABLE @Temp(
Date datetime,
Flag bit)
@Temp table as data from 01-04-2019 to 31-04-2020 (366 records) and flag=0
DECLARE startdate date='12-04-2019', interval int =1 OR 3
预期结果:如果间隔为 1 个月,则基于开始日期,标记将在记录下方更新为 1,其余为 0
date flag
01-04-2019 0
. 0
. 0
12-05-2019 1
. 0
. 0
12-06-2019 1
. 0
. 0
12-07-2019 1
.. 0
31-04-2020 0
如果间隔为 3 个月,则标志将更新为 1 季度
date flag
01-04-2019 0
. 0
. 0
12-07-2019 1
. 0
. 0
12-10-2019 1
. 0
. 0
12-01-2020 1
. 0
31-04-2020 0
我被困在试图得到结果。我正在使用 SQL Server 2017。
解决方案
我花了一段时间才意识到你的日期与我习惯的格式不同。
我会使用公用表表达式而不是游标。除此之外,请考虑任何给定日期和开始日期之间的月差。取该差异的模数(这就是“%”符号的含义)。如果它是 0,那么你的间隔已经被击中,所以激活你的标志。
declare
@startdate date = '04.01.2019',
@interval int = 3; -- or 1, or whatever
with
dates as (
select @startdate dt, 1 flag
union all
select ap.nextDt,
flag =
case
when day(ap.nextDt) <> day(@startdate) then 0
when (month(ap.nextDt) - month(@startdate)) % @interval = 0 then 1
else 0
end
from dates
cross apply (select nextDt = dateadd(day,1,dt)) ap
where dt <= dateadd(year,1,@startdate)
)
select *
from dates
option (maxrecursion 367)
推荐阅读
- swift4 - 通过在 Swift 4 中将鼠标悬停在其上来返回 NSTableView 的行索引
- python - 如何单击鼠标悬停后变为可见的元素
- console - 是否可以为 google colab 获取控制台(如在 R 工作室中)?
- python - 如何使用 pytest-django 在每个会话中只创建一次用户对象?
- operating-system - 先到先服务器算法的调度队列
- c# - 微服务之间的 Service Fabric wcf 通信
- javascript - Firestore 将函数返回添加到数据库
- ios - Swift Segue - 当现有的过渡或演示发生时;导航堆栈将不会更新
- python - 将json数据的特定元素转换为python对象
- node.js - Firebase CORS 策略仅针对某些功能阻止