如何在SQL Server 2005数据库查询中选择第n行

时间:2012-02-02 20:31:10

标签: sql sql-server-2005

SQL Server 2005查询如下......

SELECT ClgId 
FROM IdMaker_DB  
WHERE Course = 'B-Tech' AND [Class] = 'Ist Year'
AND Branch = 'Computer Science and Engineering' 
ORDER BY ClgId

工作正常并选择Computer Science and Engineering Ist Year的所有条目 但是只选择第一行,我该如何选择第n行......

3 个答案:

答案 0 :(得分:3)

select * from (
 SELECT ClgId ,row_number() over (order by ClgId) as rn  FROM IdMaker_DB 
where Course ='B-Tech' and [Class]='Ist Year'

 and Branch='Computer Science and Engineering'   ) a where rn=n   --replace the n

答案 1 :(得分:0)

SELECT top 1 ClgId 
FROM IdMaker_DB  
where Course ='B-Tech' 
and [Class]='Ist Year'
and Branch='Computer Science and Engineering' 
and clgid not in 
    (SELECT top N - 1 ClgId 
    FROM IdMaker_DB  
    where Course ='B-Tech' 
    and [Class]='Ist Year'
    and Branch='Computer Science and Engineering' 
    ORDER BY ClgId)
ORDER BY ClgId

答案 2 :(得分:-3)

SELECT TOP 1 * 
FROM   student 
WHERE  id IN 
       ( 
        SELECT TOP n id 
        FROM student 
       ) 
ORDER BY id DESC