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

标签 sql sql-server join

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

相关文章:

sql - 如何为每个公司的每种产品类型获得最便宜的产品?

sql-server - 使 varchar(50) 列唯一

mysql - MS Access 连接到两个数据库

r - 反连接但只返回 "previous"缺失行

mysql - MySQL 中的 JOIN 查询产生错误的结果

SQL 按列名的第二个字母排序

php - PDO:违反完整性约束(更新表)

java - JPA事务异常获取真正原因 - 嵌套异常

c# - 如何正确捕获调用存储过程的返回值

mysql - mysql连接问题