我有这样一张表 
 id  name  money   money2  money3    month
 
 1   张三  总10块    花5块    剩5块    1月我要把1月剩的5块  拿到第2月的总数那里 2   张三  总5块    花5块    剩0块     2月
这个要用sql怎么写  或者存储过程怎么弄。。急急急  
还有sql存储过程循环计算怎么写 能给个例子吗。谢了。

解决方案 »

  1.   


     id name total spend remain month
     
     1  张三   10     5    5   2011-1你的应该这么搞
      

  2.   

    参考这个网址http://blog.csdn.net/yongpeng_china/archive/2011/06/04/6525609.aspx
    里面有SQL高级编程,也有几个SQL编程的循环语句
      

  3.   

    按月数 把money3 移下来当money ?还是不得劲啊。不知道LINQ能实现不。
      

  4.   

    用临时表
    把每个用户的最大id(最后一条应该是最新的,如果是按时间月份插入的话)查出来放入临时表
    再读取临时表 游标逐一取出每个用户的name  money3
    插入原表,产生每个用户最新的月份记录money2 money3字段为空--
    统计花费的时候 再更新money2 money3(问题:根据什么更新?用户最大ID?name?)即使写出来
    那不得每个月必须得在恰当的时间(每月最后一天最后一秒?)跑一次存储过程?
    建议如楼上诸位之言,将表设计优化下
    这样的表适宜用逻辑呈现在报表中
      

  5.   

    貌似这个问题你在SQL版问过,没有解决吗?
      

  6.   

    declare @tb table(id int,[name] varchar(20),[money] float, money2 float, money3 float, [month] int)
    insert into @tb
    select 1,'张三',10,5,5,1 union all
    select 2,'张三',5,5,2,2 union all
    select 3,'张三',10,5,1,3 union all
    select 4,'张三',5,5,0,4 union all
    select 5,'李四',10,5,5,1 union all
    select 6,'李四',5,5,0,2 union all
    select 7,'李四',10,5,5,3 union all
    select 8,'李四',5,5,0,4select id,[name],[money]=isnull([money]+(select money3 from @tb where [name]=a.[name] and [month]=a.[month]-1),[money])
    ,money2,money3,[month] from @tb a
      

  7.   

    declare @tb table(id int,[name] varchar(20),[money] float, money2 float, money3 float, [month] int)
    insert into @tb
    select 1,'张三',10,5,5,1 union all
    select 2,'张三',5,5,2,2 union all
    select 3,'张三',10,5,1,3 union all
    select 4,'张三',5,5,0,4 union all
    select 5,'李四',10,5,5,1 union all
    select 6,'李四',5,5,0,2 union all
    select 7,'李四',10,5,5,3 union all
    select 8,'李四',5,5,0,4select id,[name],[money]=isnull([money]+(select money3 from @tb where [name]=a.[name] and [month]=a.[month]-1),[money])
    ,money2,money3,[month] from @tb a
    /*
    1 张三 10 5 5 1
    2 张三 10 5 2 2
    3 张三 12 5 1 3
    4 张三 6 5 0 4
    5 李四 10 5 5 1
    6 李四 10 5 0 2
    7 李四 10 5 5 3
    8 李四 10 5 0 4
    */
      

  8.   

     很强大的需求.. create table testDemo
    (
     总 int ,
     剩 int,
     dates int ,
    )insert into testDemo values(100,80,1)
    insert into testDemo values(80,60,2)
    insert into testDemo values(60,40,3)
    insert into testDemo values(40,20,4) select * from testDemo
    select case testDemo.dates when a.dates+1 then a.剩 end as money11,testDemo.剩,testDemo.dates from testDemo,
    (select  剩,dates from testDemo) as a  where testDemo.dates=a.dates+1 drop table testDemo
     玩玩..