日期:2014-05-17 浏览次数:20611 次
declare @st datetime, @et datetime, @MaxT datetime set @st = '2012-08-15 00:00:00.000' set @et = '2013-08-31 00:00:00.000' set @MaxT = @st while(@maxt < @et) begin set @MaxT = dateadd(mm,1,@maxt) end if (@MaxT > @et) begin set @MaxT = dateadd(mm,-1,@maxt) end select DATEDIFF (mm, @st ,@MaxT )+ datediff(day,@MaxT,@et)*1.0/day(dateadd(mm,1,@MaxT)-day(@MaxT)) /* --------------------------------------- 12.516129032258 (1 行受影响) */
------解决方案--------------------
declare @a datetime, @b datetime, @c datetime set @a = '2012-08-15 00:00:00.000' set @b = '2013-08-01 00:00:00.000' set @c = '2013-08-31 00:00:00.000' --假设@b是恒大于@a的,大的多少未知 SELECT CASE WHEN DATEADD(mm,DATEDIFF(mm,@a,@b),@a)>=@b THEN LTRIM(DATEDIFF(mm,@a,@b)-1)+'.'+LTRIM(DATEDIFF(dd,DATEADD(mm,DATEDIFF(mm,@a,@b)-1,@a),@b)) ELSE LTRIM(DATEDIFF(mm,@a,@b))+'.'+LTRIM(DATEDIFF(dd,DATEADD(mm,DATEDIFF(mm,@a,@b),@a),@b)) END SELECT CASE WHEN DATEADD(mm,DATEDIFF(mm,@a,@c),@a)>=@c THEN LTRIM(DATEDIFF(mm,@a,@c)-1)+'.'+LTRIM(DATEDIFF(dd,DATEADD(mm,DATEDIFF(mm,@a,@c)-1,@a),@c)) ELSE LTRIM(DATEDIFF(mm,@a,@c))+'.'+LTRIM(DATEDIFF(dd,DATEADD(mm,DATEDIFF(mm,@a,@c),@a),@c)) END /* ------------------------- 11.17 (1 行受影响) ------------------------- 12.16 (1 行受影响) */
------解决方案--------------------
declare @A datetime,@B datetime,@C datetime set @A='2012-08-15 00:00:00.000' set @B='2013-08-01 00:00:00.000' set @C='2013-08-31 00:00:00.000' select convert(decimal(18,1),datediff(mm,convert(varchar(7),@A,120)+'-01',convert(varchar(7),@B,120)+'-01')) +convert(decimal(18,1),(day(@B)-day(@A))/30.0) B减A ,convert(decimal(18,1),datediff(mm,convert(varchar(7),@A,120)+'-01',convert(varchar(7),@C,120)+'-01')) +convert(decimal(18,1),(day(@C)-day(@A))/30.0) C减A /* B减A C减A --------------------------------------- --------------------------------------- 11.5 12.5 (1 row(s) affected) */