34,588
社区成员
发帖
与我相关
我的任务
分享
declare @x int
declare @y int
set @x = 2
set @y = 4
declare @tab table (id int,pid int,value int);
insert into @tab
select 1,100,2 union all select 2,100,4 union all
select 3,100,5 union all select 4,100,1 union all
select 1,101,3 union all select 2,101,4 union all
select 3,101,0 union all select 1,102,2 union all
select 2,102,5 union all select 3,102,1;
with temp
as
(
select *,px = row_number() over(partition by pid order by value) from @tab
)
select distinct b.id,b.pid,b.value
from (select * from temp where value between @x and @y) a
inner join temp b on a.pid = b.pid and (a.px + 1 = b.px or a.px - 1 = b.px or a.px = b.px)
order by b.pid,b.id
select * from [tb] where PID between
(select MIN(pid) from [tb] where value between 4 and 5)
and
(select max(pid) from [tb] where value between 4 and 5)
-- or
select * from @tab t
where id=(select max(id)+1 from @tab
where value between 4 and 5 and pid=t.pid)
union all
select * from @tab t
where id=(select min(id)-1 from @tab
where value between 4 and 5 and pid=t.pid)
union all
select id,pid,value from @tab
where value between 4 and 5
order by 2
declare @tab table (id int,pid int,value int);
insert into @tab
select 1,100,2 union all select 2,100,4 union all
select 3,100,5 union all select 4,100,1 union all
select 1,101,3 union all select 2,101,4 union all
select 3,101,0 union all select 1,102,2 union all
select 2,102,5 union all select 3,102,1;
with t1 as(
select id,pid,value from @tab where value between 4 and 5
),
t2 as(
select pid,max(id) [max],min(id) [min] from t1 group by pid
)
select t.*
from @tab t, t2
where t.pid=t2.pid and (t.id=t2.[max]+1 or t.id=t2.[min]-1)
union all
select * from t1 order by 2;
/*
1 100 2
2 100 4
3 100 5
4 100 1
1 101 3
2 101 4
3 101 0
1 102 2
2 102 5
3 102 1
*/
Declare @i int,@j int
set @i=2
set @j=4
--普通
select * from biao where VALUE between @i and @j
--特殊
select * from biao where VALUE between @i-1 and @j+1
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([ID] int,[PID] int,[VALUE] int)
insert [TB]
select 1,100,2 union all
select 2,100,4 union all
select 3,100,5 union all
select 4,100,1 union all
select 1,101,3 union all
select 2,101,4 union all
select 3,101,0 union all
select 1,102,2 union all
select 2,102,5 union all
select 3,102,1
select * from [TB]
SELECT * FROM TB WHERE [VALUE] BETWEEN 2 AND 4
/*ID PID VALUE
----------- ----------- -----------
1 100 2
2 100 4
1 101 3
2 101 4
1 102 2
(5 行受影响)
*/
SELECT * FROM TB WHERE ID <4
/*
ID PID VALUE
----------- ----------- -----------
1 100 2
2 100 4
3 100 5
1 101 3
2 101 4
3 101 0
1 102 2
2 102 5
3 102 1
(9 行受影响)*/