Sql server SQL SERVER:我需要左表中的每个id,如果该id在右表中不可用,则应复制上一行数据

Sql server SQL SERVER:我需要左表中的每个id,如果该id在右表中不可用,则应复制上一行数据,sql-server,Sql Server,例如: 表1: ID 1 2 3 4 表2: ID accNo Name Amount 1 111 aaa 400 3 111 aaa 450 1 222 ddd 500 联接后的结果表: ID accNo Name Amount 1 111 aaa 400 2 111 aaa 400 3 111 aaa 450 4 111 aaa 450 1 222 ddd 500 2 222

例如:

表1:

ID
1 
2 
3 
4 
表2:

ID  accNo Name Amount
1   111   aaa   400
3   111   aaa   450
1   222   ddd   500
联接后的结果表:

ID accNo Name Amount
1  111    aaa   400
2  111    aaa   400
3  111    aaa   450
4  111    aaa   450
1  222    ddd   500
2  222    ddd   500
3  222    ddd   500
4  222    ddd   500
我需要左表中的每个id,如果该id在右表中不可用,则应为该id复制上一行数据

请使用外部帮助,您可以查找每行的值。只需按等于或小于当前行的ID进行匹配,然后按降序获得第一个匹配,这样就可以获得具有值的最高ID

select
    t1.ID,
    t2.Name,
    T2.Amount
from table1 t1
outer apply (
    select top 1
        *
    from table2 t2
    where
        t1.ID <= t2.ID
    order by
        ID DESC
) t2
编辑:


抱歉@mxix给您带来的不便。我们能用同样的方法解决更新后的问题吗?没问题。可以,但首先需要每个ID和帐户号的每个组合。检查编辑。只需更改=即可,现在它工作正常。感谢@mxix的快速回复。
select
    t1.ID,
    t2.Name,
    T2.Amount
from (
    select distinct
        t1.ID,
        t2.accNo
    table1 t1
    inner join table2 accNoTable on
        1=1
) t1
outer apply (
    select top 1
        *
    from table2 t2
    where
        t1.accNo = t2.accNo and
        t1.ID <= t2.ID
    order by
        ID DESC
) t2
declare @t table (Id int)
insert into @t values (1),(2),(3),(4)

declare @tt table (ID int,name varchar(10),amount int)
insert into @tt(ID,name,amount)values (1,'aaa',400), (4,'ddd',500)

;with cte as 
(

select top 6 t.id,name,amount,ROW_NUMBER()OVER(ORDER BY name )RN from @t t,@tt tt

),Cte2 As (

select ROW_NUMBER()OVER(ORDER BY name )R,* from cte where cte.Id > 1
)
select R as Id,Name,amount from Cte2