2017-02-01 42 views
1

我要爲所有工作日付款金額加上非工作日運行總付款金額的。例如,我有下表中的每月每天付款金額。TSQL拿到總根據運行工作日內

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

位頭餅刷,但試試這個:

;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

我想通了這一點!對於有此問題的其他人,這裏是我的解決方案:

;with mycte as (
select * , Sum(PostingDay) Over(Order by ReceivedDate desc) grp from #payment_amounts 
) 

Select ReceivedDate, PaymentAmount, PostingDay 
, Case when PostingDay=0 then null else sum(PaymentAmount) Over(Partition by grp Order by ReceivedDate) End RunningTotal from mycte 
order by ReceivedDate 

drop table #payment_amounts 
+0

您的解決方案簡單優雅。無需選擇我的答案 –