sql >> Base de Datos >  >> RDS >> Sqlserver

Cuándo usar el operador de tabla APLICAR

En primer lugar, con apply podrías llamar a funciones con valores de tabla donde los valores de los parámetros se toman de la tabla que consulta, algo como esto:

select
    t1.col3, -- column from table
    f1.col1  -- column from function
from table1 as t1
    left outer join table2 as t2 on t2.col1 = t1.col1
    outer apply dbo.function1(t1.col1, t2.col2) as f1

o trituración de columnas xml

select
    t1.col3,
    t.c.value('@value', 'int') as value
from table1 as t1
    -- table1.col1 is xml iike <Data @Value="...">...</Data>
    outer apply t1.col1.nodes('Data') as t(c) 

Desde mi experiencia, apply es muy útil cuando tienes que hacer algún cálculo previo :

select
    t1.col3,
    a1.col1,  --calculated value
    a2.col1   -- another calculated value, first one was used
from table1 as t1
    outer apply (select t1.col1 * 5 as col1) as a1
    outer apply (select a1.col1 - 4 as col1) as a2

otro ejemplo de uso de apply es sin pivotar operación:

select
    t1.col1, c.name, c.value
from table1 as t1
    outer apply (
        select 'col1', t1.col1 union all
        select 'col2', t1.col2
    ) as c(name, value)

finalmente, aquí está su consulta implementado en términos de SQL 2005 sin usar apply :

;with cte as (
    select
        y.Name, 
        y.hoursWorked,
        x.game,
        x.NumBets,
        row_number() over(partition by x.Name order by x.NumBets) as row_num
    from y
        left outer join x on x.Name = y.Name
)
select Name, hoursWorked, game, NumBets
from cte
where row_num <= 2
order by Name, NumBets desc

consulte sql fiddle ejemplo