【发布时间】:2019-03-09 15:53:55
【问题描述】:
我有两个表 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
)
【问题讨论】:
-
这个 table2 是根据您的查询创建的..?
-
是的,我有原始的 table1,然后我创建了一个新的 table2,填补了空白。我喜欢查看不同版本的表格进行错误检查。
-
请分享您的查询以创建您的 table2...
-
既然您已经在 tab2 中填充了来自 tab1 和间隙的值,为什么还要加入 tab1 以尝试获取值来填补间隙?所需的值已经存在于 tab2 中,还是我错过了什么?
-
这就是我所做的。我在我的问题中发布了我的代码,但 sql server 不喜欢我的查询。
标签: sql sql-server join