SQL that lists x records with the Weeknumber and Monday's date for each week

StackOverflow https://stackoverflow.com/questions/20353802

  •  25-08-2022
  •  | 
  •  

Question

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
Was it helpful?

Solution

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;

Example on SQL Fiddle

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top