日期:2014-05-18  浏览次数:20583 次

选取连续的记录
表格如下:
id             se
2402 2
2402 1
1609 3
1601 2
1601 1
1505 1
0904 1
0601 6
0508 3
..               ..
..               ..

se   是不确定的tinyint,不一定是从1开始。。想选取有连续id/se   的记录(> =2条),

想得到下面的结果集合:

2402     2
2402     1
1601     2
1602     1




------解决方案--------------------
create table tbl
(
id varchar(4),
se int
)

insert into tbl
select '2402 ', 2
union all select '2402 ', 1
union all select '1609 ', 3
union all select '1601 ', 2
union all select '1601 ', 1
union all select '1505 ', 1
union all select '0904 ', 1

select * from tbl a
where exists (select 1 from tbl where a.id =id group by id having count(1)> 1 )
------解决方案--------------------
declare @t table(id varchar(10),se int)
insert @t select '2402 ',2
union all select '2402 ',1
union all select '1609 ',3
union all select '1601 ',2
union all select '1601 ',1
union all select '1505 ',1
union all select '0904 ',1
union all select '0601 ',6
union all select '0508 ',3

select * from @t a where exists(select 1 from @t where id=a.id and (se=a.se-1 or se=a.se+1))

--结果
id se
---------- -----------
2402 2
2402 1
1601 2
1601 1

(所影响的行数为 4 行)
------解决方案--------------------
declare @t table(id varchar(10),se int)
insert @t select '2402 ',2
union all select '2402 ',1
union all select '1609 ',3
union all select '1601 ',2
union all select '1601 ',1
union all select '1505 ',1
union all select '0904 ',1
union all select '0601 ',6
union all select '0508 ',3

select *
from @t a
where exists(
select 1
from
@t
where id=a.id and abs(se - a.se) = 1
)
order by a.id,a.se

/*

id se
---------- -----------
1601 1
1601 2
2402 1
2402 2
*/