Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Calculate week number of the month

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!

like image 537
Nick Avatar asked Feb 07 '11 23:02

Nick


People also ask

How do I get the week number in SQL query?

The WEEK() function returns the week number for a given date (a number from 0 to 53).

How do I display a week wise data in a month in SQL Server?

How Do You Group Data by Week in SQL Server? SQL Server provides a function called DATEPART() , which returns a specified part (year, quarter, month, week, hour, minute, etc.) of a specified date. ORDER BY DATEPART(week, RegistrationDate);

How do I get weekly week data in SQL?

WEEK() function in MySQL is used to find week number for a given date. If the date is NULL, the WEEK() function will return NULL. Otherwise, it returns the value of week which ranges between 0 to 53. The date or datetime from which we want to extract the week.


2 Answers

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
like image 143
RichardTheKiwi Avatar answered Oct 03 '22 16:10

RichardTheKiwi


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)  
like image 21
Nikhil chaturvedi Avatar answered Oct 03 '22 16:10

Nikhil chaturvedi