2

Using Oracle 11g, and the data below:

create  table ds_tmp
(col1 varchar2(5) ,date1 DATE, col3 varchar2(3));

insert into ds_tmp
values('pat1','01-JAN-2018','PND');

insert into ds_tmp
values('pat1','02-JAN-2018','MIS');

insert into ds_tmp
values('pat1','03-JAN-2018','DUP');

insert into ds_tmp
values('pat2','01-JAN-2017','MIS');

insert into ds_tmp
values('pat2','02-JAN-2017','DUP');

insert into ds_tmp
values('pat2','03-JAN-2017','DUP');

insert into ds_tmp
values('pat2','04-JAN-2017','INV');

What I need to do is: 1) group by col1 2) update col3 in the following order:

if any col3=PND then set all col3 to PND
else if any col3=MIS set all col3 to MIS
else if any col3=DUP set all col3 to DUP
else set all col3 to INV

So, using the data above we would end up with all col3 values for pat1=PND and all col3 values for pat2=MIS. I could use CASE to mimic if then else but it only selects on 1 column. I think I may need an an analytic rank function but I can't think how to code it, any suggestions appreciated.

1 Answer 1

1

You can get the adjusted value with:

select col1, date1, col3,
  case
    when count(case when col3 = 'PND' then col3 end)
           over (partition by col1) > 0 then 'PND'
    when count(case when col3 = 'MIS' then col3 end)
           over (partition by col1) > 0 then 'MIS'
    when count(case when col3 = 'DUP' then col3 end)
           over (partition by col1) > 0 then 'DUP'
  end as adj_col3
from ds_tmp;

COL1  DATE1       COL ADJ
----- ----------- --- ---
pat1  03-JAN-2018 DUP PND
pat1  02-JAN-2018 MIS PND
pat1  01-JAN-2018 PND PND
pat2  03-JAN-2017 DUP MIS
pat2  02-JAN-2017 DUP MIS
pat2  04-JAN-2017 INV MIS
pat2  01-JAN-2017 MIS MIS

Then either replace col3 with that expression in your query, or use it for an update if you actually want to change the values in the table.

The over (partition by col1) does the 'grouping' part, and the three values are evaluated in the order you wanted, so PND takes priority over MIS etc.

1
  • Well, that was quick. I thought it was some combination of case and partitiion over, I didn't realise you could combine the 2. Thanks for your help
    – DS.
    Jun 28, 2018 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.