在SQL SERVER中获取运行的日期总数

时间:2014-04-02 09:06:46

标签: sql-server tsql

我想创建一个日期的运行列表,在其上面的日期增加6周。到目前为止,我的代码给了我一个开始和结束日期。我需要显示开始和结束日期之间的6周间隔

aLearnerRef     startdate     enddate       reviewdate
------------------------------------------------------
399750423600    2013-11-27    2014-06-12    2014-01-08
399750423600    2013-11-27    2014-06-12    2014-02-19
399750423600    2013-11-27    2014-06-12    2014-04-02
399750423600    2013-11-27    2014-06-12    2014-05-14

我希望它循环直到它到达enddate之前的最后一个日期。我无法找到一种可能的方法来做到这一点。这是我到目前为止的代码:

SELECT a.aLearnerRef,  x.startdate, x.enddate
FROM aims a
inner join vStudyP s
on s.LearnerRef = a.aLearnerRef
join (SELECT aLearnerRef, min(learnstartdate) startdate, max(learnplannedenddate) enddate
        FROM aims
        GROUP BY aLearnerRef) x
on a.aLearnerRef = x.aLearnerRef
group by a.aLearnerRef,  x.startdate, x.enddate

2 个答案:

答案 0 :(得分:1)

试试这段代码,

with cte as
(
select ak.akid,sdate,edate,DATEADD(WEEK,6,sdate) rdate from ak
Union All

select ak.akid,ak.sdate,ak.edate,DATEADD(WEEK,6,rdate) rdate from ak
inner join cte on  rdate between ak.sdate and ak.edate 
where  DATEADD(WEEK,6,rdate) between ak.sdate and ak.edate 


)
select * from CTE

如果有多条记录,

with cte as
    (
    select ak.akid,sdate,edate,DATEADD(WEEK,6,sdate) rdate from ak
    Union All

    select ak.akid,ak.sdate,ak.edate,DATEADD(WEEK,6,rdate) rdate from ak
    inner join cte on  rdate between ak.sdate and ak.edate 
    where  DATEADD(WEEK,6,rdate) between ak.sdate and ak.edate 
          and cte.akid = ak.akid

    )
    select * from CTE

演示链接,http://sqlfiddle.com/#!3/31d30/5

答案 1 :(得分:0)

使用辅助数字表:

SELECT a.aLearnerRef,  dateadd(day,n,a.startdate), a.enddate
FROM aims a
inner join numbers num
on n < datediff(day,startdate, enddate)