我的数据库中有这样一张表
id a1 a2 a3 a4
1  1  3  6  2
2  5  7  8  9
3  3  7  8  9
4  4  3  2  1
5  6  7  5  4表中的id为自增关键字我现在想在最后的3行数据中搜索值为4的数据上面的情况的查询语句写不出来
也就是如果在表中来进行一个特定范围查询

解决方案 »

  1.   

    select * 
    from (select top 3 * from 表 order by id desc)t
    where a1=4 or a2=4 or a3=4 or a4=4
      

  2.   

    declare @t table(id int, a1 int)
    insert @t
    select 1,  1 union all
    select 2,  5 union all
    select 3,  3 union all
    select 4,  4 union all
    select 5,  6SELECT * FROM 
    (select top 3 * from @t order by id DESC) AS t
    WHERE id = 4/*结果
    id          a1          
    ----------- ----------- 
    4           4
    */
      

  3.   

    能不能设置一个参数,我们通过修改这个参数的大小来确定搜索的范围,比如说,我们要求在最新的20行数据中查询,或者是在最新的50行数据中查询?或者在70行到80行中间的数据进行查询?2楼中间select top 3 * from 表 order by id desc as t这样t是不是也为一张表格?能不能把t直接输出?