开发者

How I can limit result in SQL Server?

开发者 https://www.devze.com 2023-02-23 02:51 出处:网络
I have table containing data for users, I need to get only last 2 users after first user ex id-username

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 bu开发者_JS百科t with SQL Server I can't


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


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

SELECT TOP 2 *
FROM MyTable
WHERE Id > 1


With SQL Server, you can use the TOP command.


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;


You can use TOP in T-SQL:

SELECT TOP 2 FROM table_name
0

精彩评论

暂无评论...
验证码 换一张
取 消