I have a table and I need to retrieve the ID of the Second row. How to achieve that ?
By Top 2
I select the two first rows, but I need only
Certainly TOP will surfice if you simply want the TOP 2, but if you need them individually so that you can do something with those values then use the ROW_NUMBER which will give you more control over the rows you want to select
ps. I did this as i'm not sure if the OP is after a simple TOP 2 in a select. (I may be wrong!)
-- 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
you can use OFFSET
and FETCH NEXT
SELECT id
FROM tablename
ORDER BY column
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
NOTE:
OFFSET can only be used with ORDER BY clause. It cannot be used on its own.
OFFSET value must be greater than or equal to zero. It cannot be negative, else return error.
The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.
The FETCH argument is used to return a set of number of rows. FETCH can’t be used itself, it is used in conjuction with OFFSET.
I'm guessing you're using SQL 2005 or greater. The 2nd line selects the top 2 rows and by using ORDER BY ROW_COUNT DESC
, the 2nd row is arranged as being first, then it is selected using TOP 1
SELECT TOP 1 COLUMN1, COLUMN2
from (
SELECT TOP 2 COLUMN1, COLUMN2
FROM Table
) ORDER BY ROW_NUMBER DESC
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 table name and newsid column name
Use ROW_NUMBER()
to number the rows, but use TOP
to only process the first two.
try this:
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
OUTPUT:
YourColumn RowNumber
----------- --------------------
7 2
(1 row(s) affected)
with T1 as
(
select row_number() over(order by ID) rownum, T2.ID
from Table2 T2
)
select ID
from T1
where rownum=2