日期:2014-05-17  浏览次数:20581 次

求指导一条SQL语句。获取指定记录的前后几条记录
本帖最后由 xjkstar 于 2013-01-15 14:17:12 编辑
在sql 中 要获得当前值前后100条记录,sql语句怎么写?
比如当前值是B100,那么结果就是:
B000、B001……B099(前99条)、B100、(后100条)B101……B199、B200.

我是这么写的

SELECT num FROM table1
WHERE num IN 
(
( select top 100 num from table1
 where num <= 'B100' order by num desc

union 
(
select top 100 num from  table1
 where num > 'B100' order by num 
)
)
 order by num

原来没问题,今儿出现个奇怪的事情:

出现的结果类似这样子:
A150、A151、A152……B050、B051(前100条)、(后100条)B102、B103……B199、B200。

感觉这是下面这个语句的结果:
SELECT num FROM table1
WHERE num IN 
(
( select top 100 num from table1
 where num <= 'B100' order by num --desc,这里的倒序被注释掉

union 
(
select top 100 num from  table1
 where num > 'B100' order by num 
)
)
 order by num


是不是我的语句逻辑不对?求指点。
sql table

------解决方案--------------------
优化器搞的鬼
用cte吧
------解决方案--------------------
看你的结果,应该是数据库中缺少B052 到 B100直接的数据。
检查一下原表数据。
------解决方案--------------------
为何in呢,直接不好么?
 select top 100 num from table1
 where num <= 'B100' order by num desc
union all

select top 100 num from  table1
 where num > 'B100' order by num 
------解决方案--------------------
如果你的表table1是按num排好序的,你的语句就没有错误,如果不是,那你得到的结果是有问题的
num
b098
b099
a100
a001
b100
b101
a102
b102
***  b100前后2条记录(没有排序)
a100
a001
b100
b101
a102
****按你的语句结果是
b099
b100
b101
b102