简体   繁体   中英

Finding difference in two dates in same month in sql using month interval

I am trying to calculate difference in two dates using datediff function and month interval. The problem is that my dates are in the same month so when I calculate difference in months, it's 0. But for my problem, as long as I have the presence of the date, I must count it as 1.

For example:

datediff(month, '2021-01-01', '2021-01-05') 

equals 0, but for my case, I need it to be equal to 1.

Please help!

You could use a CASE statement. For example, the following code works on SQL Server:

select CASE
          WHEN datediff(month,'2021-01-01','2021-01-05') = 0 THEN 1
          ELSE datediff(month,'2021-01-01','2021-01-05')
       END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM