如何从两个或多个重复行中更新一个?我想保留一个,并用新值更新其他人。
简单示例表:
这
one|two|three
----------
1|milk|water
1|milk|water
到
one|two|three
----------
1|milk|water
1|milk|sugar
答案 0 :(得分:2)
http://www.ibexpert.net/ibe/index.php?n=Doc.TheMysteryOfRDBDBKEY
Select *, RDB$DB_KEY from MyExampleTable;
然后
Update MyExampleTable
Set Column=Value
Where RDB$DB_KEY=xxxxx;
另一种方法是使用存储过程(或执行块)并使用SQL游标变量。但这需要仔细的循环管理,所以你会跳过一行并改变第二,第三等等。
另见UPDATE ... WHERE CURRENT OF ...
的示例
https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-update.html#fblangref25-dml-tbl-update
但可能最恰当的方法是向该表添加唯一的主键列,然后使用该唯一的数字ID
答案 1 :(得分:1)
不知道您使用的是哪个版本的Firebird(从版本3.0开始支持分析函数),如果以下语法有效(我目前无法验证),您可以这样做:
update table
set three='sugar'
where row_number() over (partition by one, two)=1
否则,另一种更复杂的方法是:(未经测试)
select one, two, three
from (
select t1.one
,t1.two
,coalesce(t2.three, t1.three) as three
,row_number() over (partition by t1.one, t1.two) as row_num
from table t1
left join (
select one, two, 'sugar' as three, 1 as row_num
from (
select distinct one, two, three
from table
group by one, two, three
having count(*) > 1
)
) t2
on t1.one=t2.one
and t1.two=t2.two
and t1.row_num=t2.row_num
)