• SQL经典


    create table #T (id int,item varchar(100),day datetime,money int,out int,daynumber int)
    insert into #T
    select 1,'a','2008-5-1',60,-5,null union all
    select 2,'a','2008-5-2',61,-30,null union all
    select 3,'a','2008-5-8',30,-30,null union all
    select 4,'a','2008-5-12',10,-5,null   union all
    select 5,'b','2008-5-1',60,-5,null union all
    select 6,'b','2008-5-2',61,-30,null union all
    select 7,'b','2008-5-8',30,-30,null union all
    select 8,'b','2008-5-12',10,-5,null ;

    select  id,item,day,money,out,
        daynumber = datediff(d,day,
           (select top 1 day  from #t c where a.money <
            (select sum(- out) from #t where item=a.item and id >= a.id and id <=c.id)
           )
          )
    from #t a

    with
        T1 as (select a.item, a.day day1,b.day day2,a.money,b.out from #T a, #T b where a.item=b.item and a.day<=b.day),
        T2 as (select item, day1,day2,money, sum_out=(select sum(out) from #T1 where item=t.item and day1=t.day1 and day2<=t.day2) from #T1 as t),
        T3 as (select item, day1,min(day2)day2 from T2 where money+sum_out<0 group by item, day1)
    update a set a.daynumber=datediff(day,b.day1,b.day2) from #T a join T3 b on a.item=b.item and a.day=b.day1

    select * from #t

    1 a 2008-05-01 00:00:00.000 60 -5 7
    2 a 2008-05-02 00:00:00.000 61 -30 10
    3 a 2008-05-08 00:00:00.000 30 -30 4
    4 a 2008-05-12 00:00:00.000 10 -5 0
    5 b 2008-05-01 00:00:00.000 60 -5 7
    6 b 2008-05-02 00:00:00.000 61 -30 10
    7 b 2008-05-08 00:00:00.000 30 -30 4
    8 b 2008-05-12 00:00:00.000 10 -5 0

  • 相关阅读:
    robotframework中文日志显示乱码
    flask学习
    RF元素定位的例子
    rf增加产品的例子
    Django如何重设Admin密码
    c++ ,类型转换
    new,delete和malloc,free以及allocator<T>
    疑问记录本
    c 字符串常用函数
    递归和栈溢出。
  • 原文地址:https://www.cnblogs.com/Ammy/p/1196481.html
Copyright © 2020-2023  润新知