我在SQL Server 2005中的表:帮我选择查询
id student active
1 Bob 1
3 Rob 0
5 Steve 1
7 John 1
8 Mark 0
10 Dave 0
16 Nick 1
我的选择查询由给定id返回一个活跃的学生。 但我也想要返回活跃的prev和next学生的ID。如果没有prev,它将为0或null。下一个相同。
示例:对于ID = 5,我的选择数据将返回
id student prev_id next_id
5 steve 1 7
示例:对于ID = 7,我的选择数据将返回
id student prev_id next_id
7 John 5 16
示例:对于ID = 16,我的选择将返回
id student prev_id next_id
16 Nick 7 0
如何编写此选择查询?
我有查询,但我无法正确获得prev id。它总是返回第一个活动的ID。
感谢
编辑: 下面是该查询我现在所拥有的。
select id, student,
(select top 1 id from test where id<7 and active=1) as prev,
(select top 1 id from test where id>7 and active=1) as next
from test where id=7--I used 7 just as an example. it will be a parameter
您的查询是什么? – Nishant 2011-03-02 07:00:28
我可以想到一些非常讨厌的相关子查询,它们会得到你想要的,但是这个要求的原因是什么?也许有不同的方式来满足这个要求。 – 2011-03-02 07:06:16
select test,student, (select test test from test where id <7 and active = 1)as prev, (select top 1 id from test where id> 7 and active = 1)as next from test where id = 7 - 我将使用7 – kheya 2011-03-02 07:06:18