Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get week of year in SQL with calendar rule?

In .NET C# there is the Calendar.GetWeekOfYear Method

public virtual int GetWeekOfYear(
DateTime time,
CalendarWeekRule rule,
DayOfWeek firstDayOfWeek)

where there is a parameter "CalendarWeekRule" to define the rules. In my case, I used CalendarWeekRule.FirstFourDayWeek to assert that a week needs to have 4 days in the same month to be considered a week.

https://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear(v=vs.110).aspx

How can I do this in SQL? Is there an equivalent function?

like image 783
Rute Lemos Avatar asked Oct 31 '25 03:10

Rute Lemos


1 Answers

DATEPART ( wk, date ) 

This will return an integer for the week from the date you provide. For further parameters of DATEPART here is the link! DATEPART TSQL

EDIT : As you asked in the comments for your question, you can change the first day of the week with SET DATEFIRST = (see values here)

like image 185
Fleury26 Avatar answered Nov 01 '25 18:11

Fleury26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!