-2

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

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

4

2 回答 2

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
于 2013-08-09T13:24:03.360 回答
2

这是 SQLFiddel 演示

以下是更新查询

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)
于 2013-08-09T13:36:51.880 回答