单个查询以在oracle中更新具有基于列值的不同值的记录

时间:2013-08-09 12:19:42

标签: sql oracle

我需要根据另一列person_id更新表格中的列family_id。每个家庭ID可以包含多个记录。我想设置从1开始的person_id值,并为每个系列增加1。

有任何单一查询吗?或者我可以为家庭设置一些循环并设置值? 使用Oracle 10g,我需要在一个包中提供这个逻辑。

2 个答案:

答案 0 :(得分:3)

我想我拥有它。这是我的简单例子:

create table test_epn
(
  person_id number,
  family_id number
);

insert into test_epn values(10, 1);
insert into test_epn values(11, 1);
insert into test_epn values(12, 1);
insert into test_epn values(20, 2);
insert into test_epn values(21, 2);

表格是:

person_id   family_id
10          1
11          1
12          1
20          2
21          2

函数row_number将允许我们重新编制索引,如下面的语句所示:

select e.*, row_number() over
            (partition by e.family_id order by e.person_id) new_person_id
from test_epn e;

person_id   family_id   new_person_id
10          1          1
11          1          2
12          1          3
20          2          1
21          2          2

现在我们“只是”必须更新表格,这要归功于这个新列new_person_id

update test_epn e
set e.person_id = (
  with w as
  (
    select f.person_id, f.family_id, row_number()
           over (partition by f.family_id order by f.person_id) new_person_id
    from test_epn f
  )
  select w.new_person_id
  from w
  where w.person_id = e.person_id
)
;

然后我们有你想要的东西:

person_id   family_id
1          1
2          1
3          1
1          2
2          2

答案 1 :(得分:2)

<强> Here is the SQLFiddel Demo

以下是更新查询

Update Temp
   set col1 = (select T3.myrank
                 from Temp T1,(select T2.id,rank() 
                                      over (partition by 
                                            T2.family_id
                                      order by T2.id) as myrank
                                 from Temp T2) T3
                where t1.id = T3.id
                  and t1.id = Temp.id)