Oracle SQL查询可在人员之间平均分配任务

时间:2018-11-16 16:34:30

标签: sql oracle

我有oracle数据库表'table_1',其中有2列,下面是几个示例行-

CaseID    PerID
35039074    
36190822    
35067334    
36246430    
35239319    
36003875    

此动态表中的记录会频繁添加。

我还有另一个oracle数据库表'table_2',其中有2列,其行数固定如下-

Name    PerID
Nokia   8385
Opppo   7698
Vivo    5684
Mi      2351

我想通过获取PerID(来自table_2)来更新table_1的“ PerID”列,并按以下方式依次分配table_1中的每个CaseID-

CaseID      PerID
35039074    8385
36190822    7698
35067334    5684
36246430    2351
35239319    8385
36003875    7698

可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

请尝试以下查询:

with cte as
(select CaseID ,PerID 
from table_2)
update table_1 set perID=CTE.PerID where caseID=CTE.PerID;

答案 1 :(得分:0)

您可以使用row_number()生成值:

with t1 as (
      select t1.*, rownum as seqnum
      from table_1 t1
     ),
     t2 as (
      select t2.*, rownum as seqnum, count(*) over () as cnt
      from table_2 t2
     ) t2
select t1.*, t2.perid
from table_1 t1 join
     table_2 t2
     on mod(t1.seqnum - 1, t2.cnt) = t2.seqnum;

如果您需要实际更新值,那么merge可能是最简单的方法。

merge into table_1 t1
    using (with t1 as (select t1.*, rownum as seqnum
                       from table_1 t1
                      ),
                      t2 as (
                       select t2.*, rownum as seqnum, count(*) over () as cnt
                       from table_2 t2
                      ) t2
                 select t1.*, t2.perid
                 from table_1 t1 join
                      table_2 t2
                      on mod(t1.seqnum - 1, t2.cnt) = t2.seqnum
                )
    on (s.caseid = t1.caseid)
when matched
    then update
        set t1.perID = s.perID;