Link to home
Start Free TrialLog in
Avatar of patriotpacer
patriotpacer

asked on

Go Back 5 business Days

Seeing if anyone knows how to query back 5 business days?

business days meaning no weekends.

So if I ran today(12/19) it would return a date of 12/13/2013
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

In your where clause can you use

 WHERE DATEPART(dw,'<<some date>>') <> 1 AND DATEPART(dw,'<<some date>>') <> 7
Avatar of vr6r
vr6r

DECLARE @daysback INT = 5

WHILE(DATEPART(DW, GETDATE() - @daysback) IN (1,7))
BEGIN
	SET @daysback = @daysback + 1
END

SELECT CONVERT(DATE,GETDATE() - @daysback, 101)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
declare	@dateStart	datetime
,	@dateEnd	datetime
,	@counter	int

-- chop off time, initialize variable
select	@dateStart	= convert(varchar,current_timestamp,101)
,	@dateEnd	= convert(varchar,current_timestamp,101)
,	@counter	= 1

-- go back 5 days
While @counter <= 5 begin
	select	@dateStart	= dateadd(dd,-1,@dateStart)
	,	@counter	= @counter + case when datepart(weekday,@dateStart) in (1,7) then 0 else 1 end
end

-- show results
select	@dateStart	
,	@dateEnd	

Open in new window

Avatar of patriotpacer

ASKER

Thank you so much for all the contributions.