读书人

这个sql语句如何写

发布时间: 2012-01-10 21:26:51 作者: rapoo

这个sql语句怎么写
比如我的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的值?

[解决办法]
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
[解决办法]

SQL code
declare @t table(fd1 int,fd2 int)insert into @tselect 20,21union all select 30,31union all select 40,41union all select 50,51-- select * from @tselect top 1 max(fd1),fd2from @twhere fd1<35group by fd1,fd2 order by fd1 DESC,fd2
[解决办法]
SQL code
declare @t table(fd1 int,fd2 int)insert into @tselect 20,21union all select 30,31union all select 40,41union all select 50,51select * from (select top 1 fd1,fd2 from @t where fd1 < 35 order by fd1 desc) a unionselect * from (select top 1 fd1,fd2 from @t where fd1 > 35 order by fd1 asc) b
[解决办法]
SQL code
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 ) 

读书人网 >VC/MFC

热点推荐