Problem in getting months in ceiling or floor in SQL Server

Problem in getting months in ceiling or floor in SQL Server



In SQL Server, I am trying to get number of months between two dates.



I want the solution like this:






i have tried below functions but desired output is not coming: DATEDIFF(dd,OPENDATE,MATURITYDATE)/30 , DATEDIFF(mm,OPENDATE,MATURITYDATE)

– P B
Sep 15 '18 at 7:58






There are many different days in a month like Jun 31 Feb 28 or 29. What's your logic to get days of month numbe?

– D-Shih
Sep 15 '18 at 8:10







i am simply assuming days of month to be 30 days. my query is that if there are 135 days then the number of months are coming 4.5 months. i want it to be 5 months(ceiling of 4.5, or in other case floor if months are 4.2 )

– P B
Sep 15 '18 at 8:18






Ok I got it, you can try my answer:)

– D-Shih
Sep 15 '18 at 8:24






For example, if the dates are 2018-01-01 and 2018-01-16. That's 15 days, so you would want 0.5 rounded up to 1 in this case. Another way to look at it is that 15 days of passed in a month of 31 days, so that's 15/31 months, which would round down to 0.

– David Dubois
Sep 16 '18 at 3:14




1 Answer
1



If you are assuming days of month to be 30 days.



DATEDIFF return integer difference days.


DATEDIFF


integer



So, you can try to use CAST(days as decimal) let the day number be float number, then do ROUND get your result.


CAST(days as decimal)


ROUND


select ROUND(CAST(DATEDIFF(dd,OPENDATE,MATURITYDATE)as decimal) /30,0 )
from T



sqlfiddle



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)