1.先做一个FUNCTION按表一来分割表二的时间段,用数组返回利率;
2.按利率的数组使用DO WHILE...LOOP来累计本金和利率。
FUNCTION要用代码来实现。

解决方案 »

  1.   

    我对你们利率和本金的业务一点都不清楚,呵呵,我给你一个方案,
    (苯办法):写两句SQL,然后用两个Recordset,在做个Function,
    作个循环,然后判断表二的记录在表的的哪个时间段里面,然后取出累计
    就是拉。
      

  2.   

    1。首先做一个FUNCTION,把表二的时间分隔,不过前提是你的利率表一定是按年来划分的。先在表二取得起始时间,并计算出起始时间的当年最后一天,从而计算出当年的月数。然后计算下一年是否是终止时间的年份,如果不是,则按上面的方法计算下去;如果是则计算到终止时间为止有多少个月份。按这个原理可以计算出到 终止时间的年数和月数。
    2。通过上面的计算,可以得到该存款每一年的存入月数和当年利率,把它们存入一个数组。
    3。利用FOR NEXT来计算现时的本金。
      

  3.   

    使用function做了一个例子,在query中调试通过。
    请注意:
    1,本范例没有提供出错处理,前提是所有数据都完整。
    2,本范例对成批计算效率不理想,只适合计算某一条记录的值
    3,对于误差的说明,由于本范例中大部分数据都采用numeric(9,2)型,对较大的数值误差会大,可以根据需要将function中使用的临时变量精度设高一点。下面是调试代码:
    create table tblTax(startyear smalldatetime,endyear smalldatetime,tax numeric(9,2))
    insert into tblTax values('1998-1-1','1998-12-31','0.03')
    insert into tblTax values('1999-1-1','1999-12-31','0.04')
    insert into tblTax values('2000-1-1','2000-12-31','0.02')create table tblAmount(startdate smalldatetime,enddate smalldatetime,amount numeric(9,2))
    insert into tblAmount values('1998-6-1','1999-4-30','1000')
    insert into tblAmount values('1999-2-1','2000-5-31','500')
    insert into tblAmount values('2000-1-1',null,'800')
    create function dbo.getSum(@startdate smalldatetime,@enddate smalldatetime,@amount numeric(9,2))
    returns numeric(9,2)
    as
    begin
    declare @startyear int,
    @endyear int,
    @curyear int,--当前年份
    @startmonth int,
    @endmonth int,
    @curamount numeric(9,2),--当年的利率加本金
    @curtaxsum numeric(9,2),--当年利率和
    @monthtax numeric(9,6)--月利率--初始化
    set @startyear=year(@startdate)
    set @endyear=year(@enddate)
    set @curyear=@startyear
    set @curtaxsum=0
    set @curamount=@amount--对每年循环,计算本金和利率和
    while @curyear<=@endyear
    begin
    select @monthtax=tax/12 from tblTax where year(startyear)=@curyear
    set @startmonth=1
    set @endmonth=12
    if @curyear=@startyear set @startmonth=month(@startdate)
    if @curyear=@endyear set @endmonth=month(@enddate)
    set @curtaxsum=@curamount*@monthtax*(@endmonth-@startmonth+1)
    set @curamount=@curamount+@curtaxsum
    set @curyear=@curyear+1
    end
    return @curamount
    end
    select *,dbo.getSum(startdate,isnull(enddate,getdate()),amount) as sum from tblAmount
      

  4.   

    一点建议:
    如果利率表中存放的一定是年利率,可以将表改成两个段(year,tax)。