declare @dt datetime ='2015-09-07' Select dateadd(day,-11,@dt), dateadd(day,-3,@dt) --where yourdtColumn> dateadd(day,-11,@dt) and yourdtColumn <= dateadd(day,-3,@dt)
Try:
declare @LastWeekThursday datetime; declare @CurrentDate date = CURRENT_TIMESTAMP; set @LastWeekThursday = DATEADD(DAY, -7 + DATEDIFF(DAY, '19000101', @CurrentDate) / 7 * 7, '19000104') select CURRENT_TIMESTAMP as Today, dateadd(day,-6, @LastWeekThursday) as StartOnFriday, @LastWeekThursday as endOnThursday
You could either use a calendar table or use some date arithmetic.
Example (date arithmetic using a reference that happens to be a Thursday):
DECLARE @dt date = CURRENT_TIMESTAMP; SELECT @dt AS [@dt], DATEADD(DAY, (DATEDIFF(DAY, '19000104', @dt) / 7) * 7, '19000104') AS prv_Thursday_inclusive, DATEADD(DAY, ((DATEDIFF(DAY, '19000104', @dt) / 7) * 7) - 6, '19000104') AS prv_Thursday_inclusive_minus_6; GO
- Calculate the number of whole 7 days between the reference date and today (... / 7)
- Multiply previous value by 7 (prv Thursday) and substract 6 days (Friday previous to previous Thursday)
Here is the same in one step:
SELECT DATEADD(DAY, ((DATEDIFF(DAY, '19000104', CURRENT_TIMESTAMP) / 7) * 7) - 6, '19000104') AS col1;
Example (using a Calendar table):
SELECT TOP (1) * FROM ( SELECT TOP (2) [date] FROM dbo.Calendar WHERE [date] <= CAST(CURRENT_TIMESTAMP AS date) AND DayOfWeekName = 'Friday' ORDER BY [date] DESC ) AS T ORDER BY [date];
The non-RDBMS mindset is to do a lot of temporal math. A set-oriented way is to use a calendar table with an ISO week-date ("yyyyWww-d") column; you can copy it off the internet. This will be a general tool for other apps.
Naomi, if this is the interval end date, should it not be "2015-09-03 59:59:00.000" to make it inclusive of all records on that day, instead "2015-09-03 00:00:00.000"?
Thanks.