Oracle
 sql >> Database >  >> RDS >> Oracle

Oracle SQL:trova CLIENTKEY duplicato e mostra un record specifico

Potresti usare una sottoquery che assegna una classifica a ciascuna riga, in modo che dove c'è una chiave duplicata (un KB, una qualsiasi altra cosa) la riga KB sia classificata più in alto; e poi filtra su quello:

-- CTE for sample data
with your_table (clientkey, clientname, department, hostkey) as (
  select '0201967/6', 'PPBOP1BOP01-JO,BLOGS', 'KB', 'PPBOP1BOP01/MSC/PPBOP1BOP01/2/B1KI0' from dual
  union all
  select '0201967/6', 'PPBOP1BOP01-JO,BLOGS', 'BS', 'PPBOP1BOP01/MSC/PPBOP1BOP01/2/B1KI0' from dual
  union all
  select '0024028/2', 'PPBOP1BOP01-FOO,BAR', 'KB', 'PPBOP1BOP01/MSC/PPBOP1BOP01/2/B2KI0' from dual
  union all
  select '0024028/2', 'PPBOP1BOP01-FOO,BAR', 'BS', 'PPBOP1BOP01/MSC/PPBOP1BOP01/2/B2KI0' from dual
  union all
  select '1746947/1', 'BSM1BSM03-THING,BOB', 'BS', 'BSM1BSM03/BSHVS/BSM1BSM03/2/B1KI0' from dual
  union all
  select '1612105/1', 'WIBU1IBU03-TREE,GREEN', 'BS', 'WIBU1IBU03/SHVS/WIBU1IBU03/3/B1KI0' from dual
)
-- actual query
select clientkey, clientname, department, hostkey
from (
  select clientkey, clientname, department, hostkey,
    rank () over (partition by clientkey
      order by case when department = 'KB' then 0 else 1 end) as rnk
  from your_table
)
where rnk = 1;

CLIENTKEY CLIENTNAME            DE HOSTKEY                            
--------- --------------------- -- -----------------------------------
0024028/2 PPBOP1BOP01-FOO,BAR   KB PPBOP1BOP01/MSC/PPBOP1BOP01/2/B2KI0
0201967/6 PPBOP1BOP01-JO,BLOGS  KB PPBOP1BOP01/MSC/PPBOP1BOP01/2/B1KI0
1612105/1 WIBU1IBU03-TREE,GREEN BS WIBU1IBU03/SHVS/WIBU1IBU03/3/B1KI0 
1746947/1 BSM1BSM03-THING,BOB   BS BSM1BSM03/BSHVS/BSM1BSM03/2/B1KI0  

Ciò consentirà comunque duplicati in altri reparti, se ciò può accadere, e includerà tutte quelle righe; escluderà solo i duplicati per KB.