tba
年份 月份 基数
2010 11 50
12 100
2011 1 80
2 70
3 60
4 55
tbb
年份 月份 消费
2010 12 40
2011 1 105
2 80
3 75
查询结果
年份 月份 当前可用基数 前期余额 本月基数
2011 4 115              60  55
**说明**
要求基数2010年11月的基数将用于2010年12月消费,
如上表所述2010年11月基数为50,12月消费40 则2011年1月的可消费基数为 2010年11月消费剩余基数+2010年12月基数 110.
如此类推.当前基数为最新一年最新一月的基数+之前消费基数所产生的余额.即:2011年4月的当前基数为2011年4月+2010(11+12)+2011(1+2+3)也就是2011年4月之前的基数与消费总和的差额.

解决方案 »

  1.   

    create table tba(年份 int, 月份 int ,基数 int) 
    go
    insert tba
    select 2010 ,11, 50 union  
    select 2010 ,12, 100  union  
    select 2011 ,1 ,80  union  
    select 2011 ,2 ,70  union  
    select 2011 ,3 ,60  union  
    select 2011 ,4 ,55 create table tbb(年份 int, 月份 int ,消费 int) 
    go
    insert tbb
    select 2010, 12, 40 union  
    select 2011, 1 ,105 union  
    select 2011, 2 ,80 union  
    select 2011, 3, 75 --查询
    select 年份,月份,基数,前期余额=(select sum(a.基数)-sum(b.消费) from tba a full join tbb b on a.年份=b.年份 and a.月份=b.月份
    where (ltrim(a.年份)+right('0'+ltrim(a.年份),2))<'201104' and ltrim(b.年份)+right('0'+ltrim(b.年份),2)<'201104'),当前可用基数=基数+(select sum(a.基数)-sum(b.消费) from tba a full join tbb b on a.年份=b.年份 and a.月份=b.月份
    where (ltrim(a.年份)+right('0'+ltrim(a.年份),2))<'201104' and ltrim(b.年份)+right('0'+ltrim(b.年份),2)<'201104')from tba  where 年份=2011 and 月份=4/*
    年份          月份          基数          前期余额        当前可用基数      
    ----------- ----------- ----------- ----------- ----------- 
    2011        4           55          60          115(所影响的行数为 1 行)
    */