我有一个 10 行的表
id values
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 j
对于@id = 5,我想在之前得到两行,在之后得到两行。
怎么能得到?
我有一个 10 行的表
id values
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 j
对于@id = 5,我想在之前得到两行,在之后得到两行。
怎么能得到?
Edit This should work as expected (hopefully):
select id, value
from [table]
where id-@id >= -2
AND id-@id <= 2
AND id-@id <> 0
Here's the running sql: http://sqlfiddle.com/#!6/ca4e5/3/0
一种可能的解决方案:
select *
from table
where id in (3, 4, 6, 7)
如果您使用的是 int 变量 @id,您可以这样做:
select *
from table
where id in (@id-2, @id-1, @id+1, @id+2)
要选择前两个:
select top 2 *
from tablename
where id < @id
order by id desc
要选择接下来的两个:
select top 2 *
from tablename
where id > @id
order by id asc