SQL Server:使用上一条记录

时间:2017-10-08 10:19:22

标签: sql-server

我尝试过使用LAG()ROW_NUMBER()等几种方法,但我无法让它正常工作......请帮助。

假设我们有这个表:

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

请注意:在我的情况下,总会有一个记录具有Balance值。这是起点,可以是0或<> 0(但不是null)。

1 个答案:

答案 0 :(得分: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