Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week number in year from date

Tags:

I am looking for a query which will return the week number from given date.

What I've already tried is this:

select datepart(wk, '2017-02-01') 

but this returns 5 instead of 6. (february 1st is the 6th week of the year).

(week numbers with red)

enter image description here

like image 626
FrenkyB Avatar asked Mar 14 '17 19:03

FrenkyB


People also ask

How do I get week number year in Excel?

How to get the week number from a date. To get the ISO week number (1-53) for a date in cell A1 , use =ISOWEEKNUM( A1 ) . The is supported in Excel 2022 and later, and Excel 2011 for Mac and later. To get the corresponding year, use =YEAR( A1 - WEEKDAY( A1 , 2) + 4) .

How do I automate the week number in Excel?

1. Select a blank cell you will return the week number, enter this formula: =WEEKNUM(B1,1), and press the Enter key.

Which function returns week number in a year?

The WEEKNUM Function[1] is an Excel DATE and TIME Function. It will return the week number of a specific date. The function will return an integer that represents a week number from 1 to 52 weeks of the year.


2 Answers

You probably need to specify the first day of your week with set datefirst:

set datefirst 1; select datepart(week, '2017-02-01'); 

returns 6


Depending on the default language, your datefirst might be set to 7.

set datefirst 7; select datepart(week, '2017-02-01'); 

returns 5

rextester demo: http://rextester.com/KEPB52852

like image 120
SqlZim Avatar answered Oct 04 '22 14:10

SqlZim


You can also consider using 'iso_week' instead of 'week' parameter in 'datepart'. This case you can avoid using 'set datefirst 1', which can be convenient if you can only use a single select.

More details here about 'iso_week': "ISO 8601 includes the ISO week-date system, a numbering system for weeks. Each week is associated with the year in which Thursday occur"

You can compare the two like this:

SELECT datepart(ISO_WEEK, '2020.01.01') -- Wed SELECT datepart(WEEK, '2020.01.01') -- Wed SELECT datepart(ISO_WEEK, '2020.01.05') -- Sun SELECT datepart(WEEK, '2020.01.05') -- Sun SELECT datepart(ISO_WEEK, '2020.01.06') -- Mon SELECT datepart(WEEK, '2020.01.06') -- Mon 

Note the difference for Sunday, 5 Jan 2020:

----------- 1 1 1 2 2 2 
like image 23
czeinerb Avatar answered Oct 04 '22 13:10

czeinerb