表名news 字段ID,TITLENAME 
字段ID值为 1,  4,  6,  7, 8
现在我要求一条SQL语句得到前三行语句的第三行记录 也就是ID是6的语句.select top 1 * from news order by id desc 还有TOP 3(前三行) 如何录入 ;毕竟我遇到的问题是ID是不知道的参数;并且只取一行记录;

解决方案 »

  1.   

    declare @n int
    set @n=3
    select top 1 * from(select top (@n) * from news order by id) a
      

  2.   

    declare @n int
    set @n=3print('select top 1 * from(select top '+ltrim(@n)+' * from news order by id) a')
      

  3.   

    --2000
    declare @n int
    set @n=3
    print('select top 1 * from(select top '+ltrim(@n)+' * from news order by id) a order by id desc')
    --2005
    declare @n int
    set @n=3
    select top 1 * from(select top (@n) * from news order by id) a order by id desc
      

  4.   

    create proc Id_proc
    declare @id int
    as
    begin
    select top 1 * from news where ID not in (select top (@n-1) ID from news)
    end
    --应用:
    exec Id_proc 3
      

  5.   

    SELECT TOP 1 ID FROM (SELECT TOP 3 ID FROM TB ORDER BY ID ) ORDER BY ID DESC
      

  6.   

    --修改一下下,呵呵...
    create proc Id_proc
    declare @id int
    as
    begin
    select top 1 * from news where ID not in (select top (@id-1) ID from news)
    end
    --应用:
    exec Id_proc 3
      

  7.   

    可以试下用Row_number()函数,可以按照自己的要求排序生成ID列  SELECT * FROM 
      (
       SELECT Row_number()over(order by id ) as Rowid,*
       FROM news
      )tempTable 
      WHERE tempTable.Rowid=3 --直接指定第几列
      

  8.   

    declare @n int
    set @n=3
    select top 1 * from(select top (@n) * from news order by id) a order by id desc
      

  9.   

    感谢大家 答案出来了select top 1 topic from (select top 3 * from news order by id asc) a order by id desc 不过 第一行最后面的那个a是什么意思啊?
      

  10.   


    就是一个别名。(select top 3 * from news order by id asc)这是一个表,其别名为a