T-SQL How to select only Second row from a table?

前端 未结 15 1263
攒了一身酷
攒了一身酷 2020-12-28 12:31

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

相关标签:
15条回答
  • 2020-12-28 12:58

    In SQL Server 2012+, you can use OFFSET...FETCH:

    SELECT
       <column(s)>
    FROM
       <table(s)>
    ORDER BY
       <sort column(s)>
    OFFSET 1 ROWS   -- Skip this number of rows
    FETCH NEXT 1 ROWS ONLY;  -- Return this number of rows
    
    0 讨论(0)
  • 2020-12-28 12:58

    No need of row number functions if field ID is unique.

    SELECT TOP 1 *
    FROM (
      SELECT TOP 2 * 
      FROM yourTable
      ORDER BY ID
    ) z
    ORDER BY ID DESC
    
    0 讨论(0)
  • 2020-12-28 12:58
    select *
    from (
      select ROW_NUMBER() OVER (ORDER BY Column_Name) as ROWNO, *
      from Table_Name
    ) Table_Name
    where ROWNO = 2
    
    0 讨论(0)
  • 2020-12-28 12:58
    SELECT TOP 2 [Id] FROM table
    
    0 讨论(0)
  • 2020-12-28 13:01

    Use TOP 2 in the SELECT to get the desired number of rows in output. This would return in the sequence the data was created. If you have a date option you could order by the date along with TOP n Clause.

    To get the top 2 rows;

    SELECT TOP 2 [Id] FROM table 
    

    To get the top 2 rows order by some field

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

    To Get only 2nd Row;

    WITH Resulttable AS 
    ( 
      SELECT TOP 2 
        *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber 
      FROM @Table 
    )  
    SELECT *
    FROM Resultstable
    WHERE RowNumber = 2
    
    0 讨论(0)
  • 2020-12-28 13:01

    I have a much easier way than the above ones.

    DECLARE @FirstId int, @SecondId int
    
        SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
        SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 
    
    SELECT @SecondId 
    
    0 讨论(0)
提交回复
热议问题