日期:2014-05-18 浏览次数:20603 次
--写个最笨,但是最好理解的写法 declare @d datetime set @d = '2011-10-03' declare @i int set @i=0 while(@d<getdate()) begin set @d=dateadd(month,1,@d) set @i=@i+1 end if(datediff(d,getdate(),@d)>15) set @i=@i-1 select @i as age /* age ----------- 4 */
------解决方案--------------------
DECLARE @D DateTime SET @D = '2011-01-16' select DATEDIFF(mm,@D,GETDATE())-1+ --月份掐头去尾 (case when DATEDIFF(d,@d,convert(varchar(8),dateadd(mm,1,@d),120)+'01')+DATEDIFF(d,convert(varchar(8),getdate(),120)+'01',GETDATE())>15 then 1 else 0 end) /* ----------- 13 (1 行受影响) */
------解决方案--------------------
--貌似这样就可以,楼主可以测试一下,有问题留言 declare @d datetime set @d= '2011-10-03' declare @t datetime set @t= '2012-02-09' select datediff(month,@d,getdate())+ceiling((day(@t)-day(@d))/15) as age /* age ----------- 4 */
------解决方案--------------------
declare @d datetime set @d= '2011-02-28' declare @t datetime set @t= '2011-03-30' select case when day(@d)< 15 and day(@t)>=15 then datediff(mm,@d,@t)+ (case when abs(day(@d)-day(@t))>=15 then 1 else 0 end) when day(@d)< 15 and day(@t)< 15 then datediff(mm,@d,@t) when day(@d)>= 15 and day(@t)< 15 then datediff(mm,@d,@t) when day(@d)>= 15 and day(@t)>= 15 then datediff(mm,@d,@t)+ (case when abs(day(@d)-day(@t))>=15 then 1 else 0 end) end as age 试试这个