Here's a little snippet that should do what you need.
DECLARE @firstOfYear DATETIME
SET @firstOfYear = STR(Year(GETDATE()), 4)+'-01-01 00:00:00'
SELECT DATEDIFF(ww, @firstOfYear - ((DATEPART(dw, @firstOfYear) + 5) % 7), GETDATE())
Keep in mind that if you want to set the week start to on a different day, just change the +5
to the value based on 7 - dw
. This is for MSSQL.
This works by getting the first day of the year and finding the day of the starting week on or before that day. Then we get the number of weeks between whatever date was passed in and that "first" week start. If you want to allow any date to be passed in, just replace all GETDATE
calls with your parameter and you should be good to go. If you need a single select statement:
SELECT
DATEDIFF(ww, day1 - ((DATEPART(dw, day1) +5) % 7), GETDATE())
FROM
(SELECT CAST(STR(Year(GETDATE()), 4)+'-01-01 00:00:00' AS DATETIME) day1) d