declare @month varchar(32)
Declare cur_Month CURSOR FOR select distinct month from SCM_yingshouyingfumingxi where month between '201205' and '201208' order by month 
FOR READ ONLY
 
OPEN cur_Monthfetch next from cur_Month into @monthwhile @@fetch_status=0
begin
 select @month month,kehu,jine_c,jine_fapiao,jine_shoukuan 
 from(
   select 
   kehu,sum(case when direction=1 then shoukuanjine else -shoukuanjine end) as jine_c,0 jine_fapiao,0 jine_shoukuan
   from SCM_yingshouyingfumingxi
   where fapiaozhuangtai=0 and Month<@month  group by kehu)a
fetch next from cur_Month into @month
endclose cur_Month
deallocate cur_Month
这个搜索出来是这样的 

解决方案 »

  1.   

    谢谢,这个问题已经解决了
    不过出现个新的问题,在这个游标中计算出来的数据,怎么用select将它再次搜索出来。
      

  2.   

    定义一个临时表或者变量表,把结果插进去
    declare @month varchar(32)
    DECLARE @t TABLE([month] INT, kehu VARCHAR(50),jine_c VARCHAR(50),jine_fapiao VARCHAR(50),jine_shoukuan VARCHAR(50))Declare cur_Month CURSOR FOR select distinct month from SCM_yingshouyingfumingxi where month between '201205' and '201208' order by month  
    FOR READ ONLY
     
    OPEN cur_Monthfetch next from cur_Month into @monthwhile @@fetch_status=0
    BEGIN
    INSERT INTO @t

     select @month month,kehu,jine_c,jine_fapiao,jine_shoukuan  
     from(
      select  
      kehu,sum(case when direction=1 then shoukuanjine else -shoukuanjine end) as jine_c,0 jine_fapiao,0 jine_shoukuan
      from SCM_yingshouyingfumingxi
      where fapiaozhuangtai=0 and Month<@month group by kehu)a
    fetch next from cur_Month into @month
    endclose cur_Month
    deallocate cur_Month
    SELECT * FROM @t
      

  3.   

    追问,能不能,把上述语句,作为一张表,实现select * from (上述表的内容) a ??