0

I have table containing data for users, I need to get only last 2 users after first user ex

id-username
1-john
2-fredrek
3-sara
4-sarah

I need to get fredrek, sara - how do I do this in SQL Server ??

I know to do that with MySQL I use LIMIT1,2 but with SQL Server I can't

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kareem Nour Emam
  • 1,054
  • 4
  • 14
  • 27
  • 3
    same thing already discussed: http://stackoverflow.com/questions/971964/limit-10-20-in-sqlserver – Senthil Apr 10 '11 at 09:34

5 Answers5

2

To avoid 2 x TOP you can use ROW_NUMBER (note: you can't use ROW_NUMBER output directly in the WHERE clause of a single statement )

;WITH cRN AS
(
  SELECT
     ROW_NUMBER() OVER (ORDER BY id) AS rn,
     username
  FROM
     mytable
)
SELECT username
FROM cRN
WHERE rn BETWEEN 2 AND 3
gbn
  • 422,506
  • 82
  • 585
  • 676
1

You can use TOP, restricting in the WEHRE clause, not to take the first register

SELECT TOP 2 *
FROM MyTable
WHERE Id > 1
pcofre
  • 3,976
  • 18
  • 27
0

You can use TOP in T-SQL:

SELECT TOP 2 FROM table_name
gbn
  • 422,506
  • 82
  • 585
  • 676
ChristiaanV
  • 5,401
  • 3
  • 32
  • 42
0

With SQL Server, you can use the TOP command.

NKCSS
  • 2,716
  • 1
  • 22
  • 38
0

You have to make a dual query:

   select * from ( select top 10 * from (
    select top 20 * from table_name order by 1 asc 
    ) as tb_name order by 1 desc
    ) as tb_name_last 
    order by whathever;
pcmind
  • 990
  • 10
  • 12