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

Consulta SQL:¿Cómo puedo obtener datos de la fila con el número 1000 directamente?

row_number es el mejor enfoque, pero como solo desea una sola fila, asegúrese de mirar el plan. Podría resultar mejor identificar la fila deseada y luego volver a unirla a la tabla original para recuperar columnas adicionales.

WITH T1
     AS (SELECT *,
                ROW_NUMBER() OVER (ORDER BY number) AS RN
         FROM   master..spt_values)
SELECT name,
       number,
       type,
       low,
       high,
       status
FROM   T1
WHERE  RN = 1000;

Da

WITH T2
     AS (SELECT number,
                type,
                name,
                ROW_NUMBER() OVER (ORDER BY number) AS RN
         FROM   master..spt_values)
SELECT TOP 1 C.name,
             C.number,
             C.type,
             C.low,
             C.high,
             C.status
FROM   T2
       CROSS APPLY (SELECT *
                    FROM   master..spt_values v
                    WHERE  v.number = T2.number
                           AND v.type = T2.type
                           AND ( v.name = T2.name
                                  OR ( v.name IS NULL
                                       AND T2.name IS NULL ) )) C
WHERE  RN = 1000;  

Da