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

SQL:¿cómo limitar una combinación en la primera fila encontrada?

La palabra clave aquí es PRIMERO . Puede usar la función analítica FIRST_VALUE o construcción agregada FIRST .
Para FIRST o LAST el rendimiento nunca es peor y con frecuencia mejor que el equivalente FIRST_VALUE o LAST_VALUE construir porque no tenemos un tipo de ventana superfluo y, como consecuencia, un menor costo de ejecución:

select table_A.id, table_A.name, firstFromB.city 
from table_A 
join (
    select table_B.id2, max(table_B.city) keep (dense_rank first order by table_B.city) city
    from table_b
    group by table_B.id2
    ) firstFromB on firstFromB.id2 = table_A.id 
where 1=1 /* some conditions here */
;

Desde que 12c introdujo el operador LATERAL , así como CROSS/OUTER APPLY se une, permite usar una subconsulta correlacionada en el lado derecho de JOIN cláusula:

select table_A.id, table_A.name, firstFromB.city 
from table_A 
cross apply (
    select max(table_B.city) keep (dense_rank first order by table_B.city) city
    from table_b
    where table_B.id2 = table_A.id 
    ) firstFromB
where 1=1 /* some conditions here */
;