我有一个表(水果),其中包含以下列
Fruit_Name(varchar2(10)) | IsDuplicate Number(1)
Mango 0
Orange 0
Mango 0
我要做的是将IsDuplicate列更新为1,其中Fruit_Name在Distinct中,即
Fruit_Name(varchar2(10)) | IsDuplicate Number(1)
Mango 1
Orange 1
Mango 0
我该怎么做?
答案 0 :(得分:4)
据我所知,应该这样做
update fruits
set is_duplicate =
(
select case
when dupe_count > 1 and row_num = 1 then 1
else 0
end as is_dupe
from (
select f2.fruit_name,
count(*) over (partition by f2.fruit_name) as dupe_count,
row_number() over (partition by f2.fruit_name order by f2.fruit_name) as row_num,
rowid as row_id
from fruits f2
) ft
where ft.row_id = fruits.rowid
and ft.fruit_name = fruits.fruit_name
)
修改强>
但是,为什么不创建返回信息的视图,而不是实际更新表。根据表的大小,它可能更有效。
create view fruit_dupe_view
as
select fruit_name,
case
when dupe_count > 1 and row_num = 1 then 1
else 0
end as is_duplicate
from (
select fruit_name,
count(*) over (partition by fruit_name) as dupe_count,
row_number() over (partition by fruit_name order by fruit_name) as row_num
from fruits
) ft
答案 1 :(得分:0)
换句话说,您的表首先缺少唯一键,因此它不是SQL旨在处理的内容。
但是,您可以尝试向每行添加顺序主键。然后,您可以轻松编写UPDATE查询,将所有行设置为1,COUNT> 1和key = MIN(键)。
换句话说,你真的要看你的数据库设计。关系数据库不应包含“重复”。您需要将某些内容标记为重复的事实意味着您的表首先设计错误。数据库甚至不应该允许重复输入其数据。