Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week number of month SQL Server

Tags:

sql-server

I am trying to find the week number of a particular month given a date, so I want to know which week is that for given month

Example if I enter

  • 2016 Feb 2 ---> Week 1
  • 2016 Feb 9 ---> Week 2
  • 2016 June 2 ---> week 1
  • 2016 Jan 25 ---> week 5

Can I achieve this in a T-SQL query?

I have seen the following option

DATEPART(wk, BookingTimeStamp)

But that gives the week number of the year, not the month

The idea is to build result per week for a given month

like image 321
makdu Avatar asked Oct 31 '25 12:10

makdu


1 Answers

The first result using "SQL Server and Weeks in Month" returned this article. It shows two ways using DATEPART along with other date parsing functions. Here is one solution:

DECLARE @MyDate DATETIME =GETDATE()

SELECT DATEDIFF(WEEK, DATEADD(MONTH, DATEDIFF(MONTH, 0, @MyDate), 0), @MyDate) +1
like image 82
Ross Bush Avatar answered Nov 04 '25 07:11

Ross Bush