日期:2014-05-18 浏览次数:20453 次
set nocount on declare @a table(starttime datetime,endtime datetime,qty int) insert into @a select '2008/08/12','2010/03/06',790 select t.*,year(t.starttime1) [year], days=datediff(day,t.starttime1,t.endtime1), qty1=ceiling(datediff(day,t.starttime1,t.endtime1)*(select cast(qty as dec(18,4))/datediff(day,starttime,endtime) from @a)) from ( select starttime1=case when year(dateadd(yy,b.id-1,a.starttime)) = year(a.starttime) then a.starttime else ltrim(year(dateadd(yy,b.id-1,a.starttime)))+'/01/01' end, endtime1=case when year(a.endtime) > year(dateadd(yy,b.id-1,a.starttime)) then ltrim(year(dateadd(yy,b.id-1,a.starttime)))+'/12/31' else a.endtime end from @a a, (select id from sysobjects where id<=(select datediff(yy,starttime,endtime)+1 from @a) ) as b ) t -->结果(有点尾差) starttime1 endtime1 year days qty1 ----------------------- ---------------------- ---- ---- ---- 2008-08-12 00:00:00.000 2008-12-31 00:00:00.000 2008 141 196 2009-01-01 00:00:00.000 2009-12-31 00:00:00.000 2009 364 504 2010-01-01 00:00:00.000 2010-03-06 00:00:00.000 2010 64 89