我有两个表table1和table2,如下所示。你可以看到时间上有间隙。
table1
date item time amount
----------------------------
1/1/2000 a 1 100
1/1/2000 a 2 100
1/1/2000 a 3 200
1/1/2000 a 6 300
1/1/2000 b 1 100
1/1/2000 b 2 100
1/1/2000 b 5 200
2/1/2000 a 1 500
2/1/2000 a 3 500
2/1/2000 a 4 550
我也有一个table2,我会填补其中的空缺。
table2
date item time amount new
-------------------------------------------
1/1/2000 a 1 100 N
1/1/2000 a 2 100 N
1/1/2000 a 3 200 N
1/1/2000 a 4 Y <-- added amount should be 200
1/1/2000 a 5 Y <-- added amount should be 200
1/1/2000 a 6 300 N
1/1/2000 b 1 100 N
1/1/2000 b 2 100 N
1/1/2000 b 3 Y <-- added amount should be 100
1/1/2000 b 4 Y <-- added amount should be 100
1/1/2000 b 5 200 N
2/1/2000 a 1 500 N
2/1/2000 a 2 500 N
2/1/2000 a 3 Y <-- added amount should be 500
2/1/2000 a 4 550 N
“金额”这一行的间隔应该取上一次/前一次的值。我已经成功找到了缺失的行并添加了间隔行,但是我尝试将金额复制到间隔行中却没有成功。我查看了Stackoverflow中类似的问题,并尝试了解决方案,但仍然不起作用,例如:
update t2
set t2.amount = t1.amount
from table2 t2
inner join table1 t1 on t2.date = t1.date and t1.item = t2.item
where t2.new = 'Y'
and t2.time > (select t2.time
from table1 t3
where max(t3.time) < t2.time)
update t2
set t2.amount = t1.amount
from table1 t1
inner join table2 t2 on t1.date = t2.date and t1.item = t2.item
where t2.new = 'Y' and max(t1.time) < t2.time
有人知道如何访问上一行的数量吗?游标可以解决问题,但那是最后的手段。谢谢您从百忙之中抽出时间来帮助。
添加我的创建表代码:
create table #table1 (or #table2)
(
date smalldatetime,
item char(1),
[time] int,
amount int
,new char(1) -- for new row flag
)