0

I am working on a project and need to pull last 13 weeks of data. I have tried datediff in filter but it is pulling extra weeks. I have already set datefirst to 1 but still not getting desired result.

WHERE clause is

DATEDIFF(WEEK,dt.date_key,getdate())<=13

Mudassir
  • 31
  • 5
  • 1
    Does this answer your question? [How to get week of year in SQL with calendar rule?](https://stackoverflow.com/questions/47459525/how-to-get-week-of-year-in-sql-with-calendar-rule) – squillman Apr 11 '22 at 21:24

2 Answers2

0

I have managed to get the answer. Put below in where clause and it has worked as expected.

d.date_key is my date column.

d.date_key >= DATEADD(dd,  0, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, GETDATE())) - 13, 0)) and d.date_key <= DATEADD(dd,  6, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, GETDATE())) - 1, 0))
cursorrux
  • 1,382
  • 4
  • 9
  • 20
Mudassir
  • 31
  • 5
0

Try this code:

SELECT date_key FROM tbl WHERE date_key  BETWEEN DATEADD(week, -13,GETDATE()) AND  DATEADD(week, -1,GETDATE())
Mostafa
  • 32
  • 8