我正在使用JOIN执行SQL UPDATE,但该JOIN可以匹配多个值。假设我们有以下表格:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | A 1 | X
2 | B 1 | Y
3 | C 3 | Z
我执行以下查询:
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
Table_2 t2 ON t1.col_a = t2.col_a;
结果如下:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | X 1 | X
2 | B 1 | Y
3 | Z 3 | Z
我需要做的是使用匹配的最后一个值更新Table_1
;所以在这种情况下,我需要这个结果:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | Y 1 | X
2 | B 1 | Y
3 | Z 3 | Z
答案 0 :(得分:2)
如果你有办法在Table_2中定义记录的顺序(最后是什么意思?),你可以使用窗口函数来过滤Table_2,只包括匹配的每组记录的最后一条记录:
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
(SELECT col_a, col_b,
ROW_NUMBER() OVER (PARTITION BY col_a
ORDER BY <order by field list goes here> DESC) AS RNo
FROM Table_2) t2 ON t1.col_a = t2.col_a AND t2.RNo=1;
在特殊情况下,按字段顺序是col_b,那么您可以简单地使用(这适用于所有版本的SQL Server):
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
(SELECT col_a, MAX(col_b) AS col_b
FROM Table_2
GROUP BY col_a) t2 ON t1.col_a = t2.col_a;
答案 1 :(得分:0)
假设&#34;最后&#34; value是最大值,您可以通过cte汇总。
use test
go
/*
create table Table_1 (col_a int, col_b nchar(1));
create table Table_2 (col_a int, col_b nchar(1));
insert Table_1 values
(1,N'A'),
(2,N'B'),
(3,N'C');
insert Table_2 values
(1,N'X'),
(1,N'Y'),
(3,N'Z');
*/
with cte_maxT2 as
(
select col_a, max(col_b) col_b
from Table_2
group by col_a
)
select t1.*,c.*
from Table_1 t1
join cte_maxT2 c on c.col_a=t1.col_a