面试1 SQL SERVER 查询第20行到30之间的数据

时间:2023-03-08 17:21:32

SQL SERVER 查询第20行到30之间的数据

1.先查询前20行的ID,后查询除去20条记录的前10条记录

SELECT TOP 10 * FROM tbBank
WHERE BankID NOT IN(SELECT TOP 20 BankID FROM tbBank ORDER BY BankID ASC)

2.先查询前20行记录最大的ID,后查询大于该值的前10条记录

SELECT TOP 10 * FROM tbBank
WHERE BankID>(SELECT MAX(BankID) FROM (SELECT TOP 20 BankID FROM tbBank ORDER BY BankID ASC)AS TEMP)

3.SQL SERVER 2005 以后使用 ROW_NUMBER() 函数

SELECT * FROM (SELECT *,ROW_NUMBER() OVER(ORDER BY BankID ASC) AS Num FROM tbBank )AS TempTable
WHERE Num BETWEEN 21 AND 30