如何在sql中计算天数 [英] How to calculate days in sql

查看:342
本文介绍了如何在sql中计算天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算月份。

选择DATEDIFF(M,'31 -Mar-2014','1-Jun-2014')

结果为3

但它应该是2个月bcoz第3个月还没有完成。

How to calculate month .
select DATEDIFF(M,'31-Mar-2014','1-Jun-2014')
result is 3
but it should be 2 month bcoz 3rd month has not completed.

推荐答案





请详细说明。



DateDiff



希望这将清除概念。
Hi,

Kindly go through this.

DateDiff

Hope this will clear the concepts.


嗨Amit,



答案3是正确的。



1)开始日期是31-Mar所以它将从4月算起,可能

和结束日期是1-Jun所以它也算在内,包括Jun。



选择DATEDIFF(M,'31 -Mar-2014' ,'2014年6月1日')

回答:3





2)如果你想要结果应该是2个手段

选择DATEDIFF(月,'31 -Mar-2014','2014年5月31日')

回答:2
Hi Amit,

The answer 3 is correct .

1) The start date is 31-Mar so it will count from Apr,may
and end date is 1-Jun so it will count itself including Jun also.

select DATEDIFF(M,'31-Mar-2014','1-Jun-2014')
answer :3


2) If u want the result should be 2 means
select DATEDIFF(Month,'31-Mar-2014','31-May-2014')
answer:2


嗨Amit,


首先只使用Datediff,根据您的方便,您将无法获得确切的月份数。

原因 :Datediff将返回已经过的月份边界数。



如果您想要按照确切的天数返回月份数,请尝试以下查询。< br $> b $ b

Hi Amit,

First of all using only Datediff you won't be getting the exact month count as per your convenient.
Reason : Datediff will just return the number of Month boundaries that have been passed.

If you want month count should be returned as per exact days elapsed,try below query.

declare @startdate datetime
declare @enddate datetime
set @startdate='31-March-2014'
set @enddate='01-June-2014'



select case
        when @startdate > @enddate then NULL
        when DATEPART(day,@startdate) > DATEPART(day,@enddate) then   DATEDIFF(month,@startdate,@enddate)-1
            else DATEDIFF(month,@startdate,@enddate) end as Count_of_month





: - )



:-)


这篇关于如何在sql中计算天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆