Reputation: 2293
I'm looking for an SQL query that would provide me a list of the Weeknumber and the Monday's date for that particular week.
For example:
WeekNumber DateMonday
39 2013-09-23
40 2013-09-30
... ...
The following justs produces one week
select
(DATEPART(ISO_WEEK,(CAST(getdate() as DATETIME)))) as WeekNumber,
DATEADD(wk, DATEDIFF(d, 0, CAST(getdate() as DATETIME)) / 7, 0) AS DateMonday
Upvotes: 0
Views: 74
Reputation: 69789
If you don't have a numbers table you can generate a list of sequential numbers on the fly using system tables:
e.g
SELECT Number = ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.all_objects;
If you need to extend this for more numbers you can CROSS JOIN tables:
SELECT Number = ROW_NUMBER() OVER(ORDER BY a.object_id)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;
Then you just need to add/subtract these number of weeks from your starting date:
DECLARE @Monday DATE = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0);
WITH Numbers AS
( SELECT Number = ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.all_objects
)
SELECT WeekNumber = DATEPART(ISO_WEEK, w.DateMonday),
w.DateMonday
FROM ( SELECT DateMonday = DATEADD(WEEK, - n.Number, @Monday)
FROM Numbers n
) w;
This is a verbose way of doing this for step by step clarity, it can be condensed to:
SELECT WeekNumber = DATEPART(ISO_WEEK, w.DateMonday),
w.DateMonday
FROM ( SELECT DateMonday = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - ROW_NUMBER() OVER(ORDER BY object_id), 0)
FROM sys.all_objects
) w;
Aaron Bertrand has done some in depth comparisons ways of generating sequential lists of numbers:
Of course the easiest way to do this would be to create a calendar table
Upvotes: 1