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)
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)
5条答案
按热度按时间6yjfywim1#
You probably need to specify the first day of your week with
set datefirst
:returns
6
Depending on the default language, your
datefirst
might be set to7
.returns
5
rextester demo: http://rextester.com/KEPB52852
pftdvrlh2#
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:
Note the difference for Sunday, 5 Jan 2020:
qlvxas9a3#
You can get the week number from a specific column which contains a date by using:
This is taken from the DATEPART functions available below:
doinxwow4#
I know this is very old, but it might help somebody. If you mean you want the exact number of week in some given date, then you might use this query:
SELECT WEEK("2022-05-29"); --> 22
resource: https://www.w3schools.com/sql/func_mysql_week.asp
pn9klfpd5#
For week starting on Monday, without using "set datefirst":
select datepart(iso_week, '2023-03-22')
Because in a SQL view you cannot set datefirst which is a session variable. I found the right documentation:
ISO Week Number You can also return the ISO week number from a date by using the iso_week argument. ISO weeks start on Mondays and the first week of a year contains January 4 of that year.