日期:2014-05-18 浏览次数:20709 次
select cast(convert(varchar(8),dateadd(dd,num-1,'20120601'),112) as int) as f_date
into ta
from (select top 1000 num=row_number() over(order by getdate()) from sys.objects,sys.columns)t
where dateadd(dd,num-1,'20120601')<='20120630'
go
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([instance_id] varchar(3),[start_date] int,[end_date] int,[ini_investment] numeric(10,3))
insert [tb]
select 'AAA','20120601','20120627',1000000.000
go
if object_id('[tc]') is not null drop table [tc]
go
create table [tc]([instance_id] varchar(3),[code] int,[trade_date] int,[trade_type] int,[Amount] numeric(9,3))
insert [tc]
select 'AAA',600048,'20120607',0,333329.920 union all
select 'AAA',600383,'20120611',0,333331.050 union all
select 'AAA',600383,'20120625',2,302125.590
go
;with cte as(
select a.f_date,b.instance_id,b.ini_investment,c.AMOUNT
 from ta a join tb b on a.f_date between b.start_date and b.end_date
left join tc c on b.instance_id=c.instance_id and a.f_date=c.trade_date
) 
select f_date,instance_id,ini_investment,
  balance=ini_investment-isnull((select sum(AMOUNT) from cte where instance_id=t.instance_id and f_date<=t.f_date),0)
from cte t
/**
f_date      instance_id ini_investment                          balance
----------- ----------- --------------------------------------- ---------------------------------------
20120601    AAA         1000000.000                             1000000.000
20120602    AAA         1000000.000                             1000000.000
20120603    AAA         1000000.000                             1000000.000
20120604    AAA         1000000.000                             1000000.000
20120605    AAA         1000000.000                             1000000.000
20120606    AAA         1000000.000                             1000000.000
20120607    AAA         1000000.000                             666670.080
20120608    AAA         1000000.000                             666670.080
20120609    AAA         1000000.000                             666670.080
20120610    AAA         1000000.000                             666670.080
20120611    AAA         1000000.000                             3