T-SQL ¿Cómo seleccionar solo la segunda fila de una tabla?


Tengo una tabla y necesito recuperar el ID de la Segunda fila. Cómo lograr eso ?

Por Top 2 Selecciono las dos primeras filas, pero necesito solo la segunda fila

Author: Adam Miller, 2010-09-01

15 answers

Asumiendo SQL Server 2005+ un ejemplo de cómo obtener solo la segunda fila (que creo que puede estar preguntando - y es la razón por la que top no funcionará para usted?)

set statistics io on

;with cte as
(
select * ,
ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
) 
select * from cte where rn=2

/*Just to add in what I was running RE: Comments*/
;with cte as
(
select top 2 * ,
ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
) 
select * from cte where rn=2
 21
Author: Martin Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 12:42:21

En SQL Server 2012+, puede usar DESPLAZAMIENTO...BUSCAR:

SELECT
   <column(s)>
FROM
   <table(s)>
ORDER BY
   <sort column(s)>
OFFSET 1 ROWS   -- Skip this number of rows
FETCH NEXT 1 ROW ONLY;  -- Return this number of rows
 35
Author: SQLDiver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-12 11:58:11

Use ROW_NUMBER() para numerar las filas, pero use TOP para procesar solo las dos primeras.

Prueba esto:

DECLARE @YourTable table (YourColumn int)
INSERT @YourTable VALUES (5)
INSERT @YourTable VALUES (7)
INSERT @YourTable VALUES (9)
INSERT @YourTable VALUES (17)
INSERT @YourTable VALUES (25)

;WITH YourCTE AS
(
SELECT TOP 2
    *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber
    FROM @YourTable
) 
SELECT * FROM YourCTE WHERE RowNumber=2

SALIDA:

YourColumn  RowNumber
----------- --------------------
7           2

(1 row(s) affected)
 8
Author: KM.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 11:45:50

No se necesitan funciones de número de fila si el ID del campo es único.

SELECT TOP 1 * FROM 
                   ( SELECT TOP 2 * 
                     FROM yourTable
                     ORDER BY ID
                   ) z
ORDER BY ID DESC
 7
Author: Mudassir Hasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-14 11:03:58

Supongo que estás usando SQL 2005 o superior. La 2a línea selecciona las 2 primeras filas y usando 'ORDER BY ROW_COUNT DESC", la 2a fila se organiza como primera, luego se selecciona usando TOP 1

SELECT TOP 1 COLUMN1, COLUMN2 from (
SELECT TOP 2 COLUMN1, COLUMN2 FROM Table) ORDER BY ROW_NUMBER DESC 
 6
Author: Patriotec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-29 09:29:53
with T1 as
(
select row_number() over(order by ID) rownum, T2.ID
from Table2 T2
)
select ID from T1 where rownum=2
 4
Author: Anil Soman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 11:30:37

Select top 2 [id] from table Order by [id] desc debe darle quiere que las últimas dos filas agregadas.

Sin embargo, tendrá que prestar especial atención a la cláusula order by ya que determinará la 1ª y 2ª fila devuelta.

Si la consulta se cambiara así:

Select top 2 [id] from table Order by ModifiedDate desc

Puedes obtener dos filas diferentes. Usted tendrá que decidir qué columna utilizar en su orden por declaración.

 2
Author: codingbadger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 10:45:12

Ciertamente TOP surfice si simplemente desea el TOP 2, pero si los necesita individualmente para que pueda hacer algo con esos valores, use el ROW_NUMBER que le dará más control sobre las filas que desea seleccionar

Ps. Hice esto ya que no estoy seguro de si el OP es después de un simple TOP 2 en una selección. (¡Puede que me equivoque!)

-- Get first row, same as TOP 1
SELECT [Id] FROM 
(
    SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
    FROM table
) results
WHERE results.Rownumber = 1

-- Get second row only
SELECT [Id] FROM 
(
    SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
    FROM table
) results
WHERE results.Rownumber = 2
 1
Author: kevchadders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 11:04:06

Use TOP 2 en el SELECT para obtener el número deseado de filas en la salida. Esto regresaría en la secuencia en que se crearon los datos. Si tiene una opción de fecha, puede ordenar por la fecha junto con la cláusula TOP n.

Para obtener las 2 filas superiores;

SELECT TOP 2 [Id] FROM table 

Para obtener las 2 filas superiores ordenadas por algún campo

SELECT TOP 2[ID] FROM table ORDER BY <YourColumn> ASC/DESC

Para Obtener solo la 2ª Fila;

WITH Resulttable AS 
( 
SELECT TOP 2 
    *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber 
    FROM @Table 
)  
SELECT * FROM Resultstable WHERE RowNumber=2
 1
Author: Dheer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-02 05:21:08

Puede utilizar select top 2 Id de yourtable.

 0
Author: swapneel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 10:41:01
SELECT TOP 2 [Id] FROM table
 0
Author: Szymon Kuzniak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-01 10:41:16

Esto también es útil:

SELECT
t.*
FROM
(
SELECT
e1.*,
row_number() OVER (
ORDER BY e1.Rate DESC) AS _Rank
FROM
HumanResources.EmployeePayHistory AS e1
) AS t
WHERE
t._Rank = 2
 0
Author: hims056,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-26 06:54:19

Seleccione Top 1 * from (seleccione Top 2 * from Su nombre de mesa)Yourtablecolumname ordenar por Yourtablecolumname

 0
Author: Thilak raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-03 09:31:12

Esto está funcionando desafiantemente

SELECT * FROM 
(
SELECT top 3 *, ROW_NUMBER() OVER (ORDER BY [newsid] desc) AS Rownumber
FROM news where (news_type in(2,12))
) results
WHERE results.Rownumber = 1

//news nombre de la tabla y newsid nombre de la columna

 0
Author: Kanhaiya lal Rajora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-28 16:15:58

Select * from (select ROW_NUMBER () OVER (ORDER BY Column_Name ) as ROWNO, * from Table_Name) Table_Name donde ROWNO = 2

 -1
Author: Jay Ponkia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-24 10:03:00