Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week number from dates in T-SQL

Tags:

date

tsql

How do I get the week number from dates in T-SQL?

like image 889
Kip Birgen Avatar asked Feb 23 '10 11:02

Kip Birgen


People also ask

How do I get the week of the year in SQL?

MySQL WEEKOFYEAR() Function The WEEKOFYEAR() function returns the week number for a given date (a number from 1 to 53). Note: This function assumes that the first day of the week is Monday and the first week of the year has more than 3 days. Tip: Also look at the WEEK() function.

How do I get weekly week data in SQL?

WEEK() function in MySQL is used to find week number for a given date. If the date is NULL, the WEEK() function will return NULL. Otherwise, it returns the value of week which ranges between 0 to 53. The date or datetime from which we want to extract the week.

How do I start a week from a date in SQL?

SELECT DATEADD(week, DATEDIFF(week, 0, RegistrationDate - 1), 0) AS Monday; In the expression above, we add the specified number of weeks to the 0 date. As you remember, 0 represents midnight on Monday, 1 January 1900.


2 Answers

Have a look at DATEPART

SELECT DATEPART(wk, GETDATE()) 
like image 103
Adriaan Stander Avatar answered Sep 22 '22 14:09

Adriaan Stander


It is best to use the following:

select DATEPART(ISO_WEEK, getDate())

As when you have a year with a week 53 as in the case of 2015 it give unreliable results. (Certainly on 2008 R2)

select DATEPART(WK, '01/03/2016')

Gives variable results around week 53. When run the week after 3rd Jan it produced the value 1. When run now for the same date it gives the value 2.

like image 26
Ewan Avatar answered Sep 21 '22 14:09

Ewan