34,594
社区成员
发帖
与我相关
我的任务
分享
--原始数据:@T
declare @T table(帐号 varchar(3),起算日期 varchar(8),变动日期 varchar(8),余额 money)
insert @T
select '001','20070205',20070506,1000.00 union all
select '001','20070205',20070806,1200.00 union all
select '001','20070205',20071106,1400.00 union all
select '001','20070205',29999999,1400.00 union all
select '002','20070810',20070815,500.00 union all
select '002','20070810',20070820,600.00 union all
select '002','20070810',20070821,0.00 union all
select '003','20070910',20070930,1000.00 union all
select '003','20070910',29999999,1000.0
/*
001 (1000*5+1200*26)/31
002 (5*500+10*600+11*0)/31
003 0
*/
declare @1 varchar(8),@2 varchar(8)
select @1='20070801',@2=convert(varchar(8),dateadd(month,1,@1),112)
--更改 @1 测试其它月份
declare @Days int,@Seed int
select @Days=datediff(day,@1,@2),@Seed=datediff(day,0,@1)
exec ('select top '+@Days+' iniDate=identity(int,'+@Seed+',1) into ##iniDate from syscolumns')
select a.帐号,变动日期=convert(varchar(8),cast(b.iniDate as datetime),112),c.余额
into #Result from
(select 帐号 from @T group by 帐号) a cross join ##iniDate b
left join
(select 帐号,变动日期=case when 变动日期<@1 then @1 else 变动日期 end,余额 from @T a where 变动日期=(select max(变动日期) from @T where 帐号=a.帐号 and 变动日期<@1) or left(变动日期,6)=left(@1,6)) c
on a.帐号=c.帐号 and convert(varchar(8),cast(b.iniDate as datetime),112)=c.变动日期
order by a.帐号,b.iniDate
update #Result set 余额=0 where day(变动日期)=1 and 余额 is null
update a set a.余额=(select top 1 余额 from #Result where 帐号=a.帐号 and 变动日期<=a.变动日期 and 余额 is not null order by 变动日期 desc) from #Result a
select 帐号,平均余额=avg(余额) from #Result group by 帐号
/*
帐号 平均余额
001 1167.7419
002 100.0000
003 .0000
*/
--删除临时表
drop table ##iniDate,#Result