Window Functions - Running Total with reset

后端 未结 3 489
梦如初夏
梦如初夏 2020-12-09 22:46

I am using SQL Server 2012 to build an inventory planning / reorder engine.

I have a bunch of dated transactions, call them credits and debits. I want to do two thi

3条回答
  •  时光取名叫无心
    2020-12-09 23:21

    Ugh, based on your comments, the only thing I can think to do is use a cursor, which I hate doing.

    SQL Fiddle

    declare @Date date
    declare @Qty int
    declare @RR int
    
    
    declare @running int  = 0
    
    declare @results table
    (dt date,
     qty int,
     rt int,
     rr int
    )
    
    declare C cursor for
    select TDate, Qty,
    RecommendedReplenish 
    from (
        select 
            TDate, 
            Qty,
            -1 * (CASE WHEN Qty < 0 AND SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED     PRECEDING) < 0 
                    THEN 
                CASE WHEN Qty >  SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED PRECEDING)     THEN Qty ELSE SUM(Qty) OVER (ORDER                        BY TDate ROWS UNBOUNDED PRECEDING) END
            ELSE 0 END) as RecommendedReplenish
            /* Wrong, does not account for balance resetting to zero */
        from TX 
    ) T order by TDate
    
    open c
    fetch next from c into @date,@qty,@rr
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
    
    
      set @running = @running + @qty
      if @running <0
        begin
          set @running = 0
        end
    
      insert into @results values (@date,@qty,@running,@rr)
    
      fetch next from c into @date,@qty,@rr
    end
    close c
    deallocate c
    select
    *
    from @results
    

    Which as far as I can tell, gives you the desired result. It ain't pretty, I'm sure it could use some cleanup, but it works.

    +-------------+------+-----+----+
    |     DT      | QTY  | RT  | RR |
    +-------------+------+-----+----+
    | 2014-03-01  |  20  | 20  |  0 |
    | 2014-03-02  | -10  | 10  |  0 |
    | 2014-03-03  | -20  |  0  | 10 |
    | 2014-03-04  | -10  |  0  | 10 |
    | 2014-03-05  |  30  | 30  |  0 |
    | 2014-03-06  | -20  | 10  | 10 |
    | 2014-03-07  |  10  | 20  |  0 |
    | 2014-03-08  | -20  |  0  | 20 |
    | 2014-03-09  |  -5  |  0  |  5 |
    +-------------+------+-----+----+
    

提交回复
热议问题