2017-10-08 36 views
2

我已經嘗試了幾種方法使用LAG(),ROW_NUMBER()等,但我無法得到它的工作...請幫助。SQL Server:更新表與以前的記錄值

假設我們有這個表:

Date   Time   Amount  Balance 
--------------------------------------------- 
20171001  12:44:00  102.00  102.00 
20171002  09:32:12  10.00  null 
20171002  20:00:00  123.00  null 
20171003  07:43:12  5.29  null 

我的目標是更新平衡,但這些記錄在此表中排序。

我曾嘗試使用此代碼:

with t1 as 
(
    select 
     Date, Time, Amount, Balance, 
     lag(Balance) over (order by Date, Time) Balance_old 
    from 
     table1 
) 
update table1 
set Balance = Amount + Balance_old 
where Balance_old is not null 

不過,這似乎只更新1點的記錄,而不是3在上面的例子。即使當我嘗試做類似於ROW_NUMBER()的事情時,我也沒有得到我需要的結果。是

我想有結果如下:

Date   Time   Amount  Balance 
--------------------------------------------- 
20171001  12:44:00  102.00  102.00 
20171002  09:32:12  10.00  112.00 
20171002  20:00:00  123.00  235.00 
20171003  07:43:12  5.29  240.29 

請注意:在我的情況總是有它在平衡值的記錄。這是可以爲0或<> 0(但不爲空)的起點。

+0

如何意味着記錄沒有下令 - 它看起來像他們在日期,時間順序? –

+0

是的,這是真的,但如果我只是從table1中鍵入select *,那麼它們將不會按此順序。因此我不能使用標識列(這是在我的表中,但我沒有在上面的例子中提到)。 –

+0

@StefanvanRoosmalen的平衡值與第一行的金額值相同嗎? –

回答

5

作爲其中一種方法是簡單地使用sum() over()窗口函數。

-- set up 
select * 
    into t1 
    from (
     select cast('20171001' as date) Date1, cast('12:44:00' as time) Time1, 102.00 Amount, 102.00 Balance union all 
     select cast('20171002' as date), cast('09:32:12' as time), 10.00, null union all 
     select cast('20171002' as date), cast('20:00:00' as time), 123.00, null union all 
     select cast('20171003' as date), cast('07:43:12' as time), 5.29, null 
    ) q 


-- UPDATE statement 
;with t2 as(
    select date1 
     , time1 
     , amount 
     , balance 
     , sum(isnull(balance, amount)) over(order by date1, time1) as balance1 
    from t1 
) 
update t2 
    set balance = balance1 

結果:

Date1  Time1    Amount  Balance 
---------- ---------------- ---------- ------------- 
2017-10-01 12:44:00.0000000 102.00  102.00 
2017-10-02 09:32:12.0000000 10.00  112.00 
2017-10-02 20:00:00.0000000 123.00  235.00 
2017-10-03 07:43:12.0000000 5.29  240.29 
+1

「WITH」前的分號,它將是完美的:) – lad2025

+0

@ lad2025謝謝:) –