7

I want to calculate the week number of the month,I want to calculate the week number whether its odd or even week how can I get this in TSQL ? Thanks all!

Nick
  • 115
  • 1
  • 4
  • 8

5 Answers5

8

This gives you the week of the date @dt within its month. There is a 2nd column that uses a CASE statement over the expression, to show either "Odd" or "Even"

declare @dt datetime
set @dt = GETDATE()

select
    WhichWeekOfMonth = datepart(wk, @dt)
                     - datepart(wk,dateadd(m, DATEDIFF(M, 0, @dt), 0)) + 1,
    case when (datepart(wk, @dt)
            - datepart(wk,dateadd(m, DATEDIFF(M, 0, @dt), 0)) + 1) % 2 = 1
         then 'Odd' else 'Even' end
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
  • That is a great one Richard. Can you also help with how we can do the reverse - Provided a month and the week number, can we get the first and the last dates in that week number ? – Jinith Mar 06 '17 at 08:09
4

It will give you week Number for Every month

declare @dates datetime
select @dates='2011-03-22'
SELECT datepart(dd,@dates), ceiling (cast(datepart(dd,@dates)as numeric(38,8))/7)  
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
3

How about something readable, easily customizable, and predictable...

DECLARE @dayOfMonth AS INT;
SET @dayOfMonth = DATEPART(DAY, '3/14/2013');
SELECT CASE 
    WHEN @dayOfMonth < 8 THEN 1
    WHEN @dayOfMonth < 15 THEN 2
    WHEN @dayOfMonth < 22 THEN 3
    ELSE 4
END AS weekOfMonth;
Steve Jones
  • 1,528
  • 19
  • 12
0

I think this makes the approach very obvious:

DECLARE @DayOne DATETIME
DECLARE @ThisDay DATETIME
SET @ThisDay = GETDATE()
SET @DayOne = CAST(CAST(MONTH(@ThisDay) AS VARCHAR) + '/1/' + CAST(YEAR(@ThisDay) AS VARCHAR) AS DATETIME)
SELECT (DATEPART(wk, @ThisDay) - DATEPART(wk, @DayOne) + 1) AS [Week Of Month]

SQL Server 2012 has a CONCAT function that can be used to more easily build the DayOne string:

DECLARE @DayOne DATETIME
DECLARE @ThisDay DATETIME
SET @ThisDay = GETDATE()
SET @DayOne = CAST(CONCAT(MONTH(@ThisDay), '/1/', YEAR(@ThisDay)) AS DATETIME)
SELECT (DATEPART(wk, @ThisDay) - DATEPART(wk, @DayOne) + 1) AS [Week Of Month]
B H
  • 1,730
  • 18
  • 24
0

Try this:

SELECT (DATEPART(d, '02/07/2011')/7)%2 AS WeekNo, --Replace your date column in place of '02/07/2011'
       CASE (DATEPART(d, '02/07/2011')/7)%2 
                WHEN 1 THEN 'Odd' 
                ELSE 'Even'
             END AS WeekType
Chandu
  • 81,493
  • 19
  • 133
  • 134