How to get the last week date from Sunday to Saturday - sql

I have the following table:
Date Value
4/13/2014 25
4/14/2014 35
4/15/2014 30
4/16/2014 25
4/17/2014 21
4/18/2014 20
4/19/2014 42
4/20/2014 54
4/21/2014 44
4/22/2014 47
4/23/2014 48
4/24/2014 34
4/25/2014 32
4/26/2014 18
4/27/2014 20
4/28/2014 32
4/29/2014 34
Which updates daily.
How can I have a SQL query which adds the total Value from last week (Sunday-Saturday)?
In this case, the Sunday is 4/20 and Saturday is 4/26.
I currently have the following query which gets the week from this week:
SELECT * , DATENAME(WEEKDAY, Date) AS [DAY], CAST(CONVERT(VARCHAR(12), DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()), 110) AS DATE) AS 'WeekEnding'
FROM [database].[dbo].[table]
WHERE Date >= cast(dateadd(day,1-datepart(dw, getdate()), getdate()) as date)
--SUNDAY to SATURDAY

If I understand your question correctly, you'd like to get the SUM of the Value field within the timespan of the last Sunday-Saturday. Since you said that the table is updated daily, I'll assume that you mean the last actual week, and not just the last week that happens to be in the DB.
Here's one query that sums the records by filtering between Sunday-Saturday. In your example data, the total is 277.
SELECT SUM(Value) AS TotalValue
FROM ValueTable
WHERE Date >= DATEADD(day, -((DATEPART(dw, GETDATE()) + ##DATEFIRST) % 7) - 6,
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND
Date <= DATEADD(day, -(DATEPART(dw, GETDATE()) + ##DATEFIRST) % 7,
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
Explanation: the DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) parts simply removes the time portion of the current datetime. The other part, DATEADD(day, -(DATEPART(dw, GETDATE()) + ##DATEFIRST) % 7) subtract the difference between the current date's weekday and Saturday, yield a date of last Saturday.

For Oracle you could try. IW - week number in a year, according to ISO standard:
SELECT to_char( Date , 'IW' ), SUM (Value)
FROM TableA
GROUP BY to_char( Date , 'IW' );

The simpler way to get data from last Saturday to Sunday is:
select * from my_table_name where my_date between
DATEADD(dd, DATEPART(DW,GETDATE())*-1+1, GETDATE()) AND DATEADD(dd, DATEPART(DW,GETDATE())*-1+7, GETDATE())
Where DATEADD(dd, DATEPART(DW,GETDATE())*-1+1, GETDATE()) is last Saturday and
DATEPART(DW,GETDATE())*-1+7, GETDATE()) is the coming Sunday.

Related

How to get max Saturday dates in a column of each month, without hardcoding

How to get max Saturday dates in a column of each month in SQL Server. Can someone please help me.
Now I need only the dates which has last Saturday of month.
For example,
The table has
07-08-2021 - Saturday
14-08-2021 - Saturday
21-08-2021 - Saturday
28-08-2021 - Saturday
04-09-2021 - Saturday
11-09-2021 - Saturday
18-09-2021 - Saturday
25-09-2021 - Saturday
Suppose we are in August month, I need to select last Saturday of that month( ONLY 28-08-2021)
Suppose we are in September month, I need to select last Saturday of that month( ONLY 25-09-2021)
Output:
28-08-2021
25-09-2021
assuming you have a datefield in your table (I will refer to it here as such in the below query)
with week as (
select
date_trunc('week', datefield + interval '2 day') - interval '2 day' as week_date
-- ^this adjusts the week date_trunc to start on Saturday (it starts on Monday by default)
from sometable
)
select
extract(month from week_date) as month_num,
max(week_date) as last_saturday
from week
group by month_num
note: if you only have partial data for the current month, this query will need to be altered slightly, but you didn't give me a lot to go off of here
A CTE is defined to populate the day name of entire month and then the requirement is filtered.
;with GetDates As (
select CAST('01-01-2021' as date) as StartDate, datename(dw, '09-01-2021') as Day_Name
UNION ALL
select DATEADD(day,1, StartDate), datename(dw, DATEADD(day,1, StartDate))
from GetDates
where StartDate < '09-30-2021'
)
select max(StartDate)
from GetDates where Day_Name = 'Saturday'
group by month(StartDate)
OPTION (MAXRECURSION 500)
Here is a function to calculate the Nth Weekday - which can calculate from the beginning of the month or from the end of the month.
Alter Function dbo.fnGetNthWeekDay (
#theDate datetime
, #theWeekday int
, #theNthDay int
)
Returns Table
As
Return
/*
Adapted from a version published by Peter Larrson - with minor modifications for performance
and restructured to eliminate usage of a derived table.
Inputs:
#theDate any date in the month
#theWeekday the weekday to calculate: 1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
7 = Sunday
#theNthDay the week count where positive is from beginning of the month
and negative is from end of month
Outputs:
#theDate the date entered
#theNthDate the Nth date of the month
*/
Select theDate = #theDate
, dt.nthDate
From (Values (dateadd(month, datediff(month, #theNthDay, #theDate), 0))) As mm(FirstOfMonth)
Cross Apply (Values (dateadd(day, 7 * #theNthDay - 7 * sign(#theNthDay + 1)
+ (#theWeekday + 6 - datediff(day, -53690, mm.FirstOfMonth) % 7) % 7, mm.FirstOfMonth))) As dt(nthDate)
Where #theWeekday Between 1 And 7
And datediff(month, dt.nthDate, #theDate) = 0
And #theNthDay In (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5);
Go
You can then call it like this:
Select * From dbo.fnGetNthWeekDay('2021-08-15', 6, -1) nwd

T-SQL Dynamic date range in WHERE clause (Last fiscal year + year to date)

I'm using the following WHERE clause to only load records from the last fiscal year plus a year to date.
Running without the WHERE clause, it takes 30seconds for 1mil records. With the WHERE clause, I had to stop it after 2hours.
Can you please share your thoughts
WHERE
([schema].[table].[DATE] >= DATEADD
(yy, - 1, DATEADD
(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,
CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)
)
)
)
Declare #PastFiscalYear Date
Set #PastFiscalYear= DATEADD(yy, - 1, DATEADD(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)))
WHERE
([schema].[table].[DATE] >= #PastFiscalYear )
Can you try this
This will bring back data since the previous fiscal year start date. Just change the -3 to what ever your FY offset is. -3 is for October.
[schema].[table].[DATE] >= DATEADD(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())), 0))

How to get last week date range based on current date in sql?

I have this code in crystal reports that gives me last week date range based on the current date.
First day of the week:
If DayOfWeek(currentdate) = 2 Then
currentdate
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",-1,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",-2,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",-3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",-4,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",-5,currentdate)
Else If DayOfWeek(currentdate) = 1 Then
dateadd ("d",-6,currentdate)
Last day of week:
If DayOfWeek(currentdate) = 2 Then
dateadd ("d",+6,currentdate)
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",+5,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",+4,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",+3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",+2,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",+1,currentdate)
Else If DayOfWeek(currentdate) = 1 then currentdate
How can I do the same in SQL using 2 variables to storage Monday(startdate) and Sunday(enddate)?
I found this select datepart(dw,getdate()) --6 in this site, but I do not know how to use it.
I generated some spaced out dates in the parms CTE then SELECT the CurrentDate from parms, the Sunday of the week prior to CurrentDate and the Saturday of the week prior to CurrentDate. I'm assuming that you want the dtate range to be Sunday - Saturday.
Sunday - Saturday Ranges
;WITH parms (CurrentDate) AS (
SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, -6, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 2, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 8, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 15, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 20, CURRENT_TIMESTAMP)
)
SELECT CurrentDate
, LastWeekSunday = DATEADD(dd, -1, DATEADD(ww, DATEDIFF(ww, 0, CurrentDate) - 1, 0))
, LastWeekSaturday = DATEADD(dd, 5, DATEADD(ww, DATEDIFF(ww, 0, CurrentDate) - 1, 0))
FROM parms
Monday to Sunday Ranges
;WITH parms (CurrentDate) AS (
SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, -6, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 2, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 8, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 15, CURRENT_TIMESTAMP) UNION
SELECT DATEADD(dd, 20, CURRENT_TIMESTAMP)
)
SELECT CurrentDate
, LastWeekMonday = DATEADD(dd, 0, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CurrentDate)) - 1, 0))
, LastWeekSunday = DATEADD(dd, 6, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CurrentDate)) - 1, 0))
FROM parms
If you just want the prior week's Monday to the prior week's Sunday from today rather than from a column of dates you can use this
SELECT CURRENT_TIMESTAMP
, LastWeekSunday = DATEADD(dd, 0, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CURRENT_TIMESTAMP)) - 1, 0))
, LastWeekSaturday = DATEADD(dd, 6, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CURRENT_TIMESTAMP)) - 1, 0))
This solution is tested and works. I am getting the previous week's Monday and Sunday as upper and lower bounds.
SELECT
-- 17530101 or 1753-01-01 is the minimum date in SQL Server
DATEADD(dd, ((DATEDIFF(dd, '17530101', GETDATE()) / 7) * 7) - 7, '17530101') AS [LowerLimit], -- Last Week's Monday
DATEADD(dd, ((DATEDIFF(dd, '17530101', GETDATE()) / 7) * 7) - 1, '17530101') AS [UpperLimit] -- Last Week's Sunday.
Which can be used like this in a real world query:
SELECT
*
FROM
SomeTable
WHERE
SomeTable.[Date] >= DATEADD(dd, ((DATEDIFF(dd, '17530101', GETDATE()) / 7) * 7) - 7, '17530101') AND
SomeTable.[Date] <= DATEADD(dd, ((DATEDIFF(dd, '17530101', GETDATE()) / 7) * 7) - 1, '17530101')
Here are some tests:
1. Leap Year
Current Date: 2016-02-29 00:00:00.000
Results:
LowerLimit UpperLimit
2016-02-22 00:00:00.000 2016-02-28 00:00:00.000
2. Last Week was in different year
Current Date: 2016-01-06 00:00:00.000
LowerLimit UpperLimit
2015-12-28 00:00:00.000 2016-01-03 00:00:00.000
3. Lower limit in previous month and upper limit in current month
Current Date: 2016-05-04 00:00:00.000
LowerLimit UpperLimit
2016-04-25 00:00:00.000 2016-05-01 00:00:00.000
4. Current Date is Sunday
Current Date: 2016-05-08 00:00:00.000
LowerLimit UpperLimit
2016-04-25 00:00:00.000 2016-05-01 00:00:00.000
Bill's code worked well, but I needed to make a slight edit if I wanted to get last Sunday to Saturday based on today's date.
select CURRENT_TIMESTAMP,
LastWeekSunday = DATEADD(dd, -1, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CURRENT_TIMESTAMP)) - (case datename(weekday,CURRENT_TIMESTAMP) when 'Sunday' then 0 else 1 end), 0)),
LastWeekSaturday = DATEADD(dd, 5, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, CURRENT_TIMESTAMP)) - (case datename(weekday,CURRENT_TIMESTAMP) when 'Sunday' then 0 else 1 end), 0))
Rgds - Matt
For everything date and date interval related, I'd almost always recommend using a calendar table. A table with columns representing date, week, month, year, day of week, hiliday, weekand, etc, prepopulated as needed and indexed on every column. It's only 365 rows per year.
select min(date), max(date)
from calendar
where week = datepart(week, getdate() - 7)
and year = datepart(year, getdate() - 7)
A shortened version concise syntax
last week, in my vision is the prev adjacent week, so if Im doing report during the week days, I want to receive dates of previous adjacent week Monday to Sunday.
prev Monday is DATE_ADD(CURDATE(), INTERVAL -(5 + dayofweek(CURDATE())) DAY)
prev Sunday is DATE_ADD(CURDATE(), INTERVAL -(dayofweek(CURDATE()) - 1) DAY)
then to take the report from the table need just to integrate those two in SELECT statement
select * from XXX where DateCol between DATE_ADD(CURDATE(), INTERVAL -(5 + dayofweek(CURDATE())) DAY) and DATE_ADD(CURDATE(), INTERVAL -(dayofweek(CURDATE()) - 1) DAY) order by DateCol
I'm late to this party, but wanted to add a simpler way that works for me in SQL Server (when the other examples did not).
select * from table
-- this is for the previous week:
where (datefield >= DATEADD(dd, -1, DATEADD(ww, DATEDIFF(ww, 0, GETDATE()) - 1, 0)) and datefield < DATEADD(dd, 6, DATEADD(ww, DATEDIFF(ww, 0, GETDATE()) - 1, 0)))
-- alternatively, this is for a rolling 7 days:
and DATEDIFF(day, datefield, GETDATE()) between 0 and 7

default date value of every Friday in SQL Server?

In SQL Server 2008 i want to set a default date value of every Friday to show up in the column when i insert a new record?
ALTER TABLE myTable ADD CONSTRAINT_NAME DEFAULT GETDATE() FOR myColumn
Whats the best way to show every Friday?
I want the default value to be based on the now date then knowing that the next available date is 05-07/2013
I have the following:
dateadd(d, -((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
But when passing todays date, it gave me: 2013-06-28 which is actually LAST Friday!, it should be the up and coming Friday!
SELECT DATEADD(day,-3, DATEADD(week, DATEDIFF(week, 0, current_timestamp)+1, 0)) AS LastFridayDateOfWeek
Gets the last date of current week (sunday) then subtracts 3 from that to get Friday.
Replace current_timestamp if you need a different dates friday.
EDIT:
I thought about this a bit, and if the above (Friday THIS WEEK, so for Saturday it gives the previous date) does not work, you could easily use a reference date set like so:
DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
Same thing but with no hard coded Friday/Saturday in it:
DATEADD(DAY,7 + DATEDIFF(day,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime),5),#checkDateTime)/7*7,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime), 4))
So for 20100109 is a Friday.
SET #checkDateTime = '2012-01-14 3:34:00.000'
SELECT DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
it returns "2012/1/20"
But for SET #checkDateTime = '2012-01-13 3:34:00.000' it returns "2012/1/13"
If your current query gives you last Friday, the easiest thing to do is simply to add 7 to it:
select dateadd(d, 7-((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
------------------^
SELECT CONVERT(DATE, ( CASE WHEN DATEPART(dw, GETDATE()) - 6 <= 0
THEN DATEADD(dd,
( DATEPART(dw, GETDATE()) - 6 ) * -1,
GETDATE())
ELSE DATEADD(dd, ( DATEPART(dw, GETDATE()) ) - 1,
GETDATE())
END )) AS NearestFriday
Just add 7 to the formula
SELECT DATEADD(dd,CAST(5-GETDATE() AS int)%7,GETDATE()+7)
To verify the formula:
WITH test AS (
SELECT GETDATE() AS d UNION ALL
SELECT DATEADD(dd,1,d)
FROM test WHERE d < GETDATE() + 30
)
SELECT
d AS [input],
DATEADD(dd,CAST(5-d AS int)%7,d+7) AS [output]
FROM test
To tweak the the formula, adjust the 5- and the +7

help translate this week query from Oracle PL/SQL to SQL Server 2008

I have the following query that runs in my Oracle database and I want to have the equivalent for a SQL Server 2008 database:
SELECT TRUNC( /* Midnight Sunday */
NEXT_DAY(SYSDATE, 'SUN') - (7*LEVEL)
) AS week_start,
TRUNC( /* 23:59:59 Saturday */
NEXT_DAY(NEXT_DAY(SYSDATE, 'SUN') - (7*LEVEL), 'SAT') + 1
) - (1/(60*24)) + (59/(60*60*24)) AS week_end
FROM DUAL
CONNECT BY LEVEL <= 4 /* Get the past 4 weeks */
What the query does is get the start of the week and the end of the week for the last 4 weeks. The number of weeks is arbitrary and should be easily modified in the SQL Server query I want. It generates data like the following:
WEEK_START WEEK_END
2010-03-07 00:00:00 2010-03-13 23:59:59
2010-02-28 00:00:00 2010-03-06 23:59:59
...
The part I'm currently stuck on translating is CONNECT BY LEVEL since it seems SQL Server 2008 doesn't have an equivalent. I would prefer to simply adjust a line like CONNECT BY LEVEL <= 4 and have the query generate more or fewer weeks (i.e., I don't want to have to adjust multiple UNION ALL statements).
Edit: here's what I have so far that gets the beginning and end of the current week:
SELECT week_start,
DATEADD(SECOND, -1, DATEADD(DAY, 7, week_start)) AS week_end
FROM (
SELECT CAST(
CONVERT(
VARCHAR(10),
DATEADD(DAY, 1-DATEPART(DW, GETDATE()), GETDATE()),
111
) AS DATETIME
) AS week_start
) AS week_start_view
I don't mind if the query shows the current week start and end date or if it starts at the previous week.
I modified OMG Ponies' answer because it looked like a good idea, it just had the wrong week_end value on each week and also showed future weeks instead of past weeks. I came up with the following:
WITH dates AS (
SELECT DATEADD(
DD,
1 - DATEPART(DW, CONVERT(VARCHAR(10), starting_date, 111)),
CONVERT(VARCHAR(10), starting_date, 111)
) AS midnight
FROM (
SELECT DATEADD(WEEK, -3, GETDATE()) AS starting_date
) AS starting_date_view
UNION ALL
SELECT DATEADD(DD, 7, midnight)
FROM dates
WHERE DATEADD(DD, 7, midnight) < GETDATE()
) SELECT midnight AS week_start,
DATEADD(SS, -1, DATEADD(DAY, 7, midnight)) AS week_end
FROM dates
It generates the past 4 weeks:
week_start week_end
2010-02-14 00:00:00.000 2010-02-20 23:59:59.000
2010-02-21 00:00:00.000 2010-02-27 23:59:59.000
2010-02-28 00:00:00.000 2010-03-06 23:59:59.000
2010-03-07 00:00:00.000 2010-03-13 23:59:59.000
This is better than my previous answer, I think, because it does not rely on another table having a particular number of rows. The number of weeks generated can be changed by altering only one digit: the 3 in SELECT DATEADD(WEEK, -3, GETDATE()) AS starting_date. The current week is included, and that digit represents how many additional weeks prior to the current week should be shown.
Iterate over Past Weeks up to Now, Excluding Current Week
Update: and here's a version that excludes the current week:
WITH dates AS (
SELECT DATEADD(
DD,
1 - DATEPART(DW, CONVERT(VARCHAR(10), starting_date, 111)),
CONVERT(VARCHAR(10), starting_date, 111)
) AS midnight_sunday
FROM (
SELECT DATEADD(WEEK, -4, GETDATE()) AS starting_date
) AS starting_date_view
UNION ALL
SELECT DATEADD(DD, 7, midnight_sunday)
FROM dates
WHERE DATEADD(DD, 7, midnight_sunday) <
DATEADD(
DD,
1 - DATEPART(DW, CONVERT(VARCHAR(10), GETDATE(), 111)),
CONVERT(VARCHAR(10), GETDATE(), 111)
)
) SELECT midnight_sunday AS week_start,
DATEADD(SS, -1, DATEADD(DAY, 7, midnight_sunday)) AS week_end
FROM dates
Its results:
week_start week_end
2010-02-07 00:00:00.000 2010-02-13 23:59:59.000
2010-02-14 00:00:00.000 2010-02-20 23:59:59.000
2010-02-21 00:00:00.000 2010-02-27 23:59:59.000
2010-02-28 00:00:00.000 2010-03-06 23:59:59.000
Iterate over Past Months up to Now
I later found a need for a monthly version of this query. Here is that modification:
WITH dates AS (
SELECT CAST(
FLOOR(CAST(starting_date AS DECIMAL(12, 5))) -
(DAY(starting_date) - 1) AS DATETIME
) AS month_start
FROM (
SELECT DATEADD(MONTH, -3, GETDATE()) AS starting_date
) AS starting_date_view
UNION ALL
SELECT DATEADD(MONTH, 1, month_start)
FROM dates
WHERE DATEADD(MONTH, 1, month_start) < GETDATE()
) SELECT month_start,
DATEADD(SS, -1, DATEADD(MONTH, 1, month_start)) AS month_end
FROM dates
ORDER BY month_start DESC
Use (but don't forget to vote for Sarah):
WITH dates AS (
SELECT DATEADD(DD,
1 - DATEPART(DW, CONVERT(VARCHAR(10), starting_date, 111)),
CONVERT(VARCHAR(10), starting_date, 111)
) AS midnight
FROM (SELECT DATEADD(WEEK, -3, GETDATE()) AS starting_date) AS starting_date_view
UNION ALL
SELECT DATEADD(DD, 7, midnight)
FROM dates
WHERE DATEADD(DD, 7, midnight) < GETDATE())
SELECT midnight AS week_start,
DATEADD(SS, -1, DATEADD(DAY, 7, midnight)) AS week_end
FROM dates
Previously:
Set the first day of the week to be Sunday with the SET DATEFIRST command:
SET DATEFIRST 7
The SQL Server 2005+ equivalent to Oracle's CONNECT BY LEVEL is the recursive CTE (ANSI standard btw). Use:
WITH dates AS (
SELECT DATEADD(DD,
1 - DATEPART(DW, CONVERT(VARCHAR(10), GETDATE(), 111)),
CONVERT(VARCHAR(10), GETDATE(), 111)) AS date
UNION ALL
SELECT DATEADD(dd, 7, d.date)
FROM dates d
WHERE DATEADD(dd, 7, d.date) <= DATEADD(dd, 4*7, GETDATE()))
SELECT t.date AS week_start,
DATEADD(ss, -1, DATEADD(DAY, 7, t.date)) AS week_end
FROM dates t
See this link for explaining how to get the first day of the week. To alter the number of weeks, change the DATEADD(dd, 4*7, GETDATE()), where 4 represents the number of weeks you want generated.
All you need is a set:
;WITH cte(n) AS
(
SELECT 0
UNION ALL SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
)
SELECT week_start,
DATEADD(SECOND, -1, DATEADD(DAY, 7, week_start)) AS week_end
FROM (
SELECT CAST(
CONVERT(
VARCHAR(10),
DATEADD(WEEK, -n, DATEADD(DAY, 1-DATEPART(DW, GETDATE()), GETDATE())),
111
) AS DATETIME
) AS week_start
FROM cte
) AS week_start_view;
However I will caution you that if your data is datetime and you are going to use these boundaries for query ranges, you should use an open-ended range, e.g. >= 03/07 and < 03/14. This way you don't miss out any rows that happened between 23:59:59 and midnight; as rare as they may be, they could be important.
based on your code:
SELECT DATEADD(day, weeks.week * -7, week_start) AS week_start,
DATEADD(SECOND, -1, DATEADD(DAY, (weeks.week-1) * -7, week_start)) AS week_end
FROM (
SELECT CAST(
CONVERT(
VARCHAR(10),
DATEADD(DAY, 1-DATEPART(DW, GETDATE()), GETDATE()),
111
) AS DATETIME
) AS week_start
) AS week_start_view,
( SELECT 0 AS week UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) AS weeks
Here's what I came up with. It's slightly janky in that it relies on at least one of my tables having rows >= the number of weeks I want to select. I could adjust it slightly to include the current week.
SELECT week_start,
DATEADD(SECOND, -1, DATEADD(DAY, 7, week_start)) AS week_end
FROM (
SELECT CAST(
CONVERT(
VARCHAR(10),
DATEADD(
DAY,
1-DATEPART(DW, GETDATE()),
DATEADD(DAY, -7*level, GETDATE())
),
111
) AS DATETIME
) AS week_start
FROM (
SELECT level
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY RAND()) AS level
FROM my_table_with_at_least_21_rows
) AS all_rows_view
WHERE level <= 21
) AS level_view
) AS week_start_view
This gets the past 21 weeks, starting at last week. Here's sample data:
week_start week_end
2010-02-28 00:00:00.000 2010-03-06 23:59:59.000
2010-02-21 00:00:00.000 2010-02-27 23:59:59.000
2010-02-14 00:00:00.000 2010-02-20 23:59:59.000
2010-02-07 00:00:00.000 2010-02-13 23:59:59.000
...