--我的为什么不行?--创建数据测试环境
declare @库存表a table(KehuId int,Date varchar(6),Count int)
insert into @库存表A 
select 1,'200304',1000
union all select 1,'200305',2000
union all select 1,'200306',2500
union all select 2,'200304',3000
union all select 2,'200305',4000declare @库存表B table(KehuId int,Date varchar(6),LastCount int,NewCount int)--插入当月统计数量
insert into @库存表B(KehuId,Date,NewCount,LastCount)
select KehuId,Date,Count
,(select top 1 Count from @库存表A where KehuId=a.KehuId and Date<a.Date order by Date desc)
from @库存表A a--显示处理结果
select * from @库存表B

解决方案 »

  1.   

    每个客户,每个月都只有一条记录吧? 上面的是可以处理得到的.如果一个客户,一个月有几条记录,那你怎么处理:
    例如,假设表中有如下记录:
    1  200304 1400
    1  200304 2400
    1  200305 1400那200305的LastCount是多少?
      

  2.   

    insert 表B (KehuId,[Date],LastCount,NewCount) select KehuId,[Date],[Count],(select top 1 [count] from 表A where kehuid=tem.kehuid and [date]<tem.[date] order by [date] desc) from 表A order by KehuId,[Date]不是可以?
      

  3.   

    insert 表B (KehuId,[Date],LastCount,NewCount) select KehuId,[Date],(select top 1 [count] from 表A where kehuid=tem.kehuid and [date]<tem.[date] order by [date] desc),[Count] from 表A order by KehuId,[Date]
      

  4.   

    如果仅仅是统计最好不用游标,用Left Join同样达到效果