将公共增量值更新为一组重复记录

时间:2017-10-26 16:42:00

标签: db2 db2-luw

我有这样的场景,

Col1 | Col2 | Col3 | Col4
--------------------------
1 | null| Axy | Zcd
2 | null| Axy | Zcd
3 | null| Bxy | Yef
4 | null| Bxy | Yef
5 | null| Cvw | Dgh

我正在尝试更新Col2以为重复项集分配一个公共增量值,在识别重复项后尝试使用自动增量的SQL,但问题是每行都以不同的值增加, 我在DB2 LUW 9.7中使用此查询

update tab1 t1
set t1.col2='A'|| seq_tab1.nextval  --sequence
  where exists (
    SELECT col2,trim(upper(col3)) col3,trim(upper(col4)) col4,col1 FROM tab1 t
      where (col2 ='' or col2 is null)
      and trim(upper(t1.col3)) = trim(upper(t.col3)) 
      AND trim(upper(t1.col4)) = trim(upper(t.col4)) 
      and t1.col1=t.col1
      GROUP BY col2,trim(upper(col3)),trim(upper(col4)),col1
      HAVING COUNT(*) >= 1) 
     and (t1.col2 ='' or t1.col2 is null);

结果

Col1 | Col2 | Col3 | Col4
--------------------------
1 | A1| Axy | Zcd
2 | A2| Axy | Zcd
3 | A3| Bxy | Yef
4 | A4| Bxy | Yef
5 | A5| Cvw | Dgh

预期产出

Col1 | Col2 | Col3 | Col4
--------------------------
1 | A1| Axy | Zcd
2 | A1| Axy | Zcd
3 | A2| Bxy | Yef
4 | A2| Bxy | Yef
5 | A3| Cvw | Dgh

任何建议??

2 个答案:

答案 0 :(得分:0)

尝试了我在更新中使用的此查询

select  col1,col2,col3,rn 
from (
select  col1,col2,col3
,dense_rank() over (order by col2 nulls last) as rn
from tab1
where (col1 ='' or col1 is null)
) s1

答案 1 :(得分:0)

试试这个:

update tab1 f1                                            
set f1.new=(
select 'A' || f3.rang from 
            (                                 
            select f2.Col1, 
            dense_rank() over(order by f2.Col3, f2.Col4) rang                                         
            from tab1 f2 order by f2.Col1
            ) f3                                          
where f1.Col1=f3.Col1                        
)                                                              
where exists                                                   
(                                                              
   select * from tab1 f2                                  
   where f1.Col1=f2.Col1                     
)