比如我的table_test有如下数据field1 field2
20     21
30     31
40     41
50     51查询field1=30,表中有,获得了第二条记录(30,31)
查询field1=35, 表中没有,需要获取大于35的一条和小于35的一条,共两条记录((30,31),(40,41))1 请问这个sql语句怎么写?
我的想法是,采用两步实现,
第一步:slect filed1 field2 from table_test where filed1>=35 limit 1;这样就返回了(40,41)
第二步: slect max(field1) from table_test where filed1<35;这样只把field1的值返回来了,field2字段的值没有返回。2 如何在第二步中获取field2的值?

解决方案 »

  1.   

    select top 1 * from table_test where field1 < 35 order by field1 desc
    或者照你第一种的写法
    select field1,field2 from table_test where field1 < 35 order by field1 desc limit 1
      

  2.   

    declare @t table(fd1 int,fd2 int)insert into @t
    select 20,21
    union all select 30,31
    union all select 40,41
    union all select 50,51-- select * from @tselect top 1 max(fd1),fd2
    from @t
    where fd1<35
    group by fd1,fd2 
    order by fd1 DESC,fd2
    是这意思吗?
      

  3.   


    declare @t table(fd1 int,fd2 int)insert into @t
    select 20,21
    union all select 30,31
    union all select 40,41
    union all select 50,51
    select * from (select top 1 fd1,fd2 from @t where fd1 < 35 order by fd1 desc) a 
    union
    select * from (select top 1 fd1,fd2 from @t where fd1 > 35 order by fd1 asc) b
      

  4.   

    select top 1 * from table_test 
    where  field2=( select  max(field2) from table_test where  field1=(  select  min(field1)  from table_test  where field1>=35 ))
    and fd1=(  select  min(field1)  from table_test  where field1>=35 ) 
    union 
    select top 1 * from table_test 
    where field2=( select  min(field2) from table_test where  field1=(  select  max(field1)  from table_test where field1<=35 ))
    and field1=(  select  max(field1)  from table_test  where field1<=35 )
    方法有點笨,不過好象這一條可以搞定。當值為30的時候只會有一條記錄,值為35時會有兩條記錄。