sql >> Base de Datos >  >> RDS >> Oracle

Oracle SQL:busque CLIENTKEY duplicado y muestre un registro específico

Podría usar una subconsulta que asigne una clasificación a cada fila, de modo que donde haya una clave duplicada (una KB, una cualquier otra cosa) la fila KB tenga una clasificación más alta; y luego filtra eso:

-- 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  

Esto aún permitirá duplicados en otros departamentos, si eso puede suceder, e incluirá todas esas filas; solo excluirá duplicados para KB.