I want to simply overwrite values in a column of a table with values from a column in another table. I have a table based off from another table without a unique identifier in one of the columns, so I don't want to use joins, but just update the values since the rows are in the same order. How do I do that? So far I have tried two different approaches where Approach A only put the value from the first row into every row of the updated table whereas Approach B does not work at all.
Approach A:
Update Transactions
SET Transactions.Amount = Transactions_raw.Amount
FROM Transactions_raw
Approach B:
UPDATE Transactions
SET Amount = (SELECT Amount FROM Transactions_raw)
答案 0 :(得分:0)
您需要某种join
来匹配表-即使使用人工键也是如此:
update t
set Amount = tr.Amount
from (select t.*, row_number() over (order by (select null)) as seqnum
from Transactions t
) t join
(select tr.*, row_number() over (order by (select null)) as seqnum
from Transactions_raw tr
) tr
on t.seqnum = tr.seqnum;
答案 1 :(得分:0)
您假设行的顺序相同可能会误导您。如果您在没有select
的情况下执行order by
语句,并且在两个表中都看到相同的顺序,那么这不是您要依靠的。不能保证所谓的订单。相反,您必须具有一些订购规则。有了此规则后,您可以将其放在order by
中,然后可以根据此顺序将ID列添加到两个表中。
您可以使用以下语句计算ID值:
update Transactions
set Id = row_number() over(order by ...)
然后,您可以使用常规的inner join
。