Question

In my query i need to get month part of some date using "ISO 8601"-rules. To get ISO-week there is "ISO_WEEK" can be passed as first parameter to DATEPART function. But what is for month?

ISO month is not same as calendar months...

For example, we have date "28 December 2010". Calendar month and year says that it's "12-th month of 2010", but by ISO it's a "1-th month of 2011", because ISO-month starts at first sunday(i.e. "26 December 2010") before 1-th day of month.

So how to determine ISO-month in SQL-server?

Was it helpful?

Solution

Per your definition of ISO-month you should be able to compare how close you are to the end of the month to the day of the week and know if your ISO month matches the Gregorian month or not.

DECLARE @date TABLE (d DATE, expected INT)
INSERT INTO @date VALUES 
 ('2014-03-23',3)
 ,('2014-03-24',3)
 ,('2014-03-25',3)
 ,('2014-03-26',3)
 ,('2014-03-27',3)
 ,('2014-03-28',3)
 ,('2014-03-29',3)
 ,('2014-03-30',4)
 ,('2014-03-31',4)
 ,('2014-04-01',4)
 ,('2010-12-28',1)

SET DATEFIRST 7 --sunday/default us

SELECT DATEPART(DAY,EOMONTH(d)) EndOfMonth
      ,DATEPART(DAY,d) DayOfMonth
      ,DATEPART(d,EOMONTH ( d)) - DATEPART(D,d) [EoM-DoM]
      ,DATEPART(WEEKDAY,d) DayOfWeek
      --here's the real work
      ,CASE WHEN 7 - DATEPART(WEEKDAY,d) > DATEPART(d,EOMONTH ( d)) - DATEPART(D,d)
            THEN DATEPART(MONTH,DATEADD(m,1,d))
            ELSE DATEPART(MONTH,d)
       END [iso-month]
      ,expected          
  FROM @date
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top