简体   繁体   English

具有多种方案的Oracle Group

[英]Oracle Group with multiple scenarios

I have a table where data is as given below 我有一张表,数据如下

ID  IND_ID
1   NULL
1   NULL
1   NULL
2   123
2   NULL
2   NULL
3   234
3   321
3   NULL

My requirement is to update this table in such a way that, within a group (grouping will be done based on column ID), if there is value in column IND_ID, same value should be updated to other rows in column IND_ID having null values within that group. 我的要求是以如下方式更新该表:在一个组内(将根据列ID进行分组),如果IND_ID列中有值,则应将相同值更新为IND_ID列中具有空值的其他行该组。 If column IND_ID have null value for all the records within that group, then new sequence should be generated. 如果该组中所有记录的IND_ID列的值为空,则应生成新序列。 Currently I am writing two sql for this, one for generating the sequence and other for updating.But not sure how to nullify those records within the same ID group having two different IND_ID 目前我正在为此编写两个sql,一个用于生成序列,另一个用于更新。但是不确定如何使具有两个不同IND_ID的同一ID组中的那些记录无效

Please find the query below 请在下面找到查询

    merge into table tgt 
  using (select ID, 
                IND_ID, 
                rid, 
                row_number() over (partition by ID order by IND_ID) rn 
         from   (select ID, 
                        IND_ID, 
                        rowid rid, 
                        max(IND_ID) over (partition by ID) max_b 
                 from   table) 
         where  max_b is null) src 
    on (tgt.rowid = src.rid and src.rn = 1) 
when matched then 
update set tgt.IND_ID = SEQ.nextval;
commit;
merge into table t1
using (select max(IND_ID)IND_ID,ID from table group by
ID)SRC
on (t1.ID=SRC.ID)
when matched then update set t1.IND_ID=SRC.IND_ID;
commit;

For max_b is null, I will generate a new sequence. 由于max_b为null,我将生成一个新序列。 But in the given input record, for ID=3 , we can see two different values for IND_ID.In this case, I need to nullify IND_ID for ID=3 and generate a new sequence. 但是在给定的输入记录中,对于ID = 3,我们可以看到IND_ID的两个不同值。在这种情况下,我需要将ID = 3的IND_ID无效并生成一个新序列。

My expected output is given below 我的预期输出如下

ID  IND_ID
1   434
1   434
1   434
2   123
2   123
2   123
3   435
3   435
3   435

You may find last_value() or first_value() useful in this context: 您可能会发现在这种情况下last_value()或first_value()有用:

select 
  t1.*
, first_value(ind_id) over(partition by id) fval
, row_number() over(partition by id order by UUID) rn
from table1 t1

To locate id's with no values in ind_id: 要查找ind_id中没有值的ID:

SELECT id
from table1
group by id
having max(ind_ID) IS NULL
;

http://sqlfiddle.com/#!4/9ad1f/3 http://sqlfiddle.com/#!4/9ad1f/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM