gpt4 book ai didi

SQL:使用前一行的值填充当前行

转载 作者:行者123 更新时间:2023-12-04 21:15:51 25 4
gpt4 key购买 nike

我有两个表 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
)

最佳答案

你需要找到amount的前一个非空值:

update t
set amount = (
select amount from table2
where
date = t.date and item = t.item and time = (
select max(time) from table2
where
date = t.date and item = t.item
and time < t.time and amount is not null and new = 'N'
)
)
from table2 t
where t.amount is null and t.new = 'Y'

参见 demo .

关于SQL:使用前一行的值填充当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com