zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    gearman作业服务器的工作心得
    linux下crontab 定时执行脚本笔记
    node.js async流程控制器--queue(队列)
    解决node.js express框架的跨域问题;
    2014年11月5号工作中遇见的一些问题,记录一下.
    获取表的下一个自增ID
    一个防止页面刷新后,ajax请求的数据被重置的方法
    html元素的overflow详解
    SQL 查询 技巧
    SQL RAISERROR 用法
  • 原文地址:https://www.cnblogs.com/Ammy/p/1196481.html
Copyright © 2011-2022 走看看