MS SQL Server 2008 - 我有一个db表,其中我有一小部分具有近似匹配的行,在表中的其他位置保存2列。你将如何构建一个SQL更新循环来遍历子集(record1)并搜索其匹配的副本(record2),然后从列中复制一个值(record2.columnX)来更新另一个(record1.columnX)?
在:
TxID|RecordID|ColumnA|ColumnX|ColumnY
1 |111.222 |ggg |1234 |subset1
2 |111.222 |ggg |3456 |subset2
3 |111.333 |hhh |6789 |subset1
4 |111.333 |hhh |7890 |subset2
5 |111.444 |jjj |2345 |subset1
5 |111.444 |jjj |5678 |subset2
后:
TxID|RecordID|ColumnA|ColumnX|ColumnY
1 |111.222 |ggg |1234 |subset1
2 |111.222 |ggg |1234 |subset2
3 |111.333 |hhh |6789 |subset1
4 |111.333 |hhh |6789 |subset2
5 |111.444 |jjj |2345 |subset1
5 |111.444 |jjj |2345 |subset2
自学成才,对SQL来说相对较新。耐心是值得赞赏的。
答案 0 :(得分:1)
您可以使用RecordID
对min(TxID)组内联接的更新 update my_table t1
inner join
(
select RecordID, ColumnA, ColumnX, ColumnY
from my_table
where (TxID, RecordID ) in (
select min(TxID), RecordID
from my_table
group by RecordID)
) ttt on ttt.RecordID = t1.RecordID
set t1.ColumnX = ttt.ColumnX
答案 1 :(得分:0)
我会做类似的事情:
UPDATE table t1 SET columnX=sq.columnXmin
FROM (
SELECT t2.RecordID, MIN(t2.columnX) as columnXmin
FROM table t2
GROUP BY t2.RecordID
) AS sq
WHERE t1.RecordID = sq.RecordID;
答案 2 :(得分:0)
另一种方法:
UPDATE t1
SET t1.ColumnX = t2.ColumnX
FROM @table t1
INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
AND t1.ColumnA = t2.ColumnA
AND t1.ColumnY <> t2.ColumnY
AND t1.TxID > t2.TxID -- the lowest TxID keeps its original value
或者...
UPDATE t1
SET t1.ColumnX = t2.ColumnX
FROM @table t1
INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
AND t1.ColumnA = t2.ColumnA
AND t1.ColumnY <> t2.ColumnY
AND t1.TxID < t2.TxID -- the largest TxId keeps its original value