TSQL根据工作日获得总运行

时间:2017-02-01 18:05:26

标签: tsql sum cursor

我希望所有工作日的 付款金额加上 正在运行 非付款总金额工作日。例如,我在下表中列出了每月每天的付款金额。

create table #payment_amounts
(
ReceivedDate date
,PaymentAmount decimal(13,2)
,PostingDay int
)

insert #payment_amounts values('2/1/15',100000.00,0)
insert #payment_amounts values('2/2/15',200000.00,1)
insert #payment_amounts values('2/3/15',300000.00,1)
insert #payment_amounts values('2/4/15',400000.00,1)
insert #payment_amounts values('2/5/15',500000.00,1)
insert #payment_amounts values('2/6/15',100000.00,1)
insert #payment_amounts values('2/7/15',200000.00,1)
insert #payment_amounts values('2/8/15',300000.00,0)
insert #payment_amounts values('2/9/15',400000.00,0)
insert #payment_amounts values('2/10/15',500000.00,1)

此输出如下:

ReceivedDate    PaymentAmount   PostingDay
2015-02-01  100000.00   0
2015-02-02  200000.00   1
2015-02-03  300000.00   1
2015-02-04  400000.00   1
2015-02-05  500000.00   1
2015-02-06  100000.00   1
2015-02-07  200000.00   1
2015-02-08  300000.00   0
2015-02-09  400000.00   0
2015-02-10  500000.00   1

所以我想要的是只有PostingDay = 1的行的PaymentAmount值。但如果之前的日期是PostingDay = 0,那么我想要那些PaymentAmounts的总和。所以从上面的数据来看,我希望它看起来如下:

ReceivedDate    PaymentAmount   PostingDay  RunningTotal
2/1/2015     100,000.00      -       -   
2/2/2015     200,000.00      1   300,000.00 
2/3/2015     300,000.00      1   300,000.00 
2/4/2015     400,000.00      1   400,000.00 
2/5/2015     500,000.00      1   500,000.00 
2/6/2015     100,000.00      1   100,000.00 
2/7/2015     200,000.00      1   200,000.00 
2/8/2015     300,000.00      -       -   
2/9/2015     400,000.00      -       -   
2/10/2015    500,000.00      1   1,200,000.00 

我该怎么做?

2 个答案:

答案 0 :(得分:2)

有点头疼,但试一试:

;with cte1 as (
    Select A.*
          ,LagGrp = Lag(Grp,1) over (Order by ReceivedDate)
     From (
            Select *
                  ,Grp = IIF(PostingDay=1,null,Row_Number() over (Order By ReceivedDate) - Row_Number() over (Partition By PostingDay Order By ReceivedDate))
            From  #payment_amounts
          ) A
)
Select A.ReceivedDate
      ,A.PaymentAmount
      ,A.PostingDay  
      ,RunningTotal  = (PaymentAmount + IsNull((Select sum(PaymentAmount) From cte1 Where Grp=A.LagGrp),0)) * PostingDay
 from  cte1 A      
 Order By 1

返回

enter image description here

答案 1 :(得分:1)

我想出来了!对于有这个问题的其他人,这是我的解决方案:

vForAll