我有一组包含开始日期的数据。根据开始日期,每个季度运行一个循环。 (例如,2015年3月15日的开始日期,周期为3/15/17,6/15 / 17,19 / 15/17等)。我遇到问题正确计算下一个周期日期
when datepart(mm,getdate()) <= datepart(mm, STARTDATE) and datepart(dd,getdate()) < datepart(dd, STARTDATE) then cast(dateadd(mm, (datediff(mm, STARTDATE,getdate())%3), dateadd(mm,datediff(mm, STARTDATE,getdate()),STARTDATE))as date)
when datepart(mm,getdate()) <= datepart(mm, STARTDATE) and datepart(dd,getdate()) > datepart(dd, STARTDATE) then cast(dateadd(mm, 3-(datediff(mm, STARTDATE,getdate())%3), dateadd(mm,datediff(mm, STARTDATE,getdate()),STARTDATE))as date)
when datepart(mm,getdate()) >= datepart(mm, STARTDATE) and datepart(dd,getdate()) <= datepart(dd, STARTDATE) then cast(dateadd(mm, 3-(datediff(mm, STARTDATE,getdate())%3), dateadd(mm,datediff(mm, STARTDATE,getdate()),STARTDATE))as date)
when datepart(mm,getdate()) >= datepart(mm, STARTDATE) and datepart(dd,getdate()) >= datepart(dd, STARTDATE) then cast(dateadd(mm, 3+(datediff(mm, STARTDATE,getdate())%3), dateadd(mm,datediff(mm, STARTDATE,getdate()),STARTDATE))as date)
以下是我的结果:有些是正确的,有些则不是。任何帮助将不胜感激。谢谢!
ID| Start Date| |Next Date|
1| 3/10/2015| 7/10/2017|
2| 6/3/2009| 9/3/2017|
3| 9/28/2014| 6/28/2017|
4| 9/1/2016| 9/1/2017|
5| 6/1/2015| 6/1/2018|
6| 3/15/2017| 7/15/2017|
7| 3/15/2017| 3/15/2018|
8| 3/24/2015| 6/24/2017|
9| 3/1/2016| 3/1/2018|
10| 9/6/2012| 7/6/2017|
答案 0 :(得分:0)
测试数据集:
DECLARE @dlist as TABLE(startDate datetime)
INSERT INTO @dlist VALUES ('1/1/2010'),('2/22/2011'),('4/2/2015'),('11/1/2014'),('9/9/2019')
然后尝试这样的查询。未来的日期有点滑稽,所以如果问题出现,你将不得不用一些案例陈述解决这个问题。
SELECT
startDate
, DATEADD(q, DATEDIFF(q,startDate, GETDATE()) + 1, startDate) as nextDate
FROM
@dlist
结果:
startDate nextDate
------------------------
2010-01-01 2017-07-01
2011-02-22 2017-08-22
2015-04-02 2017-07-02
2014-11-01 2017-08-01
2019-09-09 2017-09-09