0

I have a week number, like 32, and I need get the number of days left in the month starting from this week. How can I do in SQL Server?

S3S
  • 24,809
  • 5
  • 26
  • 45

2 Answers2

0

Try DATEPART ( datepart , date ) and datepart can be weekday, day, month or something like that..

Visit this https://technet.microsoft.com/en-us/library/ms174420(v=sql.105).aspx

flowers1234
  • 339
  • 2
  • 9
  • 21
0

First, you need to find the first day of the week number in question. In order to do this, we need to know what year you want as well. In the example below, I use the current year. Once this is done, then we can use DATEDIFF() to find the days left, from the start of the week number you passed in, to the end of the month.

DECLARE @WeekNo int= 32
DECLARE @Year int=datepart(year,getdate())

SELECT 
    FirstDayOfWeek =  DATEADD(wk,@WeekNo-1,DATEADD(yy,@Year-1900,0))
    ,LastDayOfMonth = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, DATEADD(wk,@WeekNo-1,DATEADD(yy,@Year-1900,0))) + 1, 0))
    ,DaysLeftInMonth = DATEDIFF(day,DATEADD(wk,@WeekNo-1,DATEADD(yy,@Year-1900,0)),DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, DATEADD(wk,@WeekNo-1,DATEADD(yy,@Year-1900,0))) + 1, 0)))
S3S
  • 24,809
  • 5
  • 26
  • 45