Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I need to some sql part in my project. I want to divide days into certain intervals
I have startdate,enddate and interval as inputs. Divide the days between startdate and enddate based on interval.

for example

if
startdate        enddate        interval
04/01/2012    20/02/2012    7

the output should be like this

04/01/2012  10/01/2012
11/01/2012  17/01/2012
18/01/2012  24/01/2012
25/01/2012  31/01/2012
01/02/2012  07/02/2012
08/02/2012  14/02/2012
15/02/2012  20/02/2012



please help me........
Posted
Updated 28-Oct-13 21:00pm
v3

Thanks for the nice question. It is not very often you find it here.
You can use Common Table Expression for this:
SQL
declare @StartDate datetime = '03-Jan-2012', 
  @EndDate datetime = '20-Feb-2012', 
  @Interval int = 7

;with cte as(
  SELECT @StartDate as StartDate, DateAdd(d, @Interval - 1, @StartDate) as EndDate
  UNION ALL
  SELECT DateAdd(d, @Interval, c.StartDate) as StartDate, DateAdd(d, @Interval * 2 - 1, c.StartDate) as EndDate
  FROM cte c WHERE DateAdd(d, @Interval * 2 - 1, c.StartDate) < @EndDate
)
SELECT * FROM cte
OPTION (MAXRECURSION 0)
 
Share this answer
 
Comments
Raja Sekhar S 29-Oct-13 0:21am    
Nice one... +5!
Please check the following query. I tried to fulfill your requirement. Let me know if it is not fulfil your requirement.

SQL
declare @StartDate datetime = '03-Jan-2012', @EndDate datetime = '20-Feb-2012', @Interval int = 6;
declare @Flag bit = 0;
while @StartDate < @EndDate
begin	
	if @Flag = 0
	begin
		set @Flag = 1;
		set @StartDate += 1;		
	end
	else
	begin
		set @StartDate += @Interval;
		set @Flag = 0;		
	end
	print @StartDate   			
end 


The above query print the date which you show in your question.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900