34,593
社区成员
发帖
与我相关
我的任务
分享
if object_id('test','U') is not null
drop table test
go
create table test
(
username varchar(10),
id int
)
go
insert into test
select 'a',1 union all
select 'a',2 union all
select 'a',3 union all
select 'b',1 union all
select 'b',3 union all
select 'b',4 union all
select 'c',1 union all
select 'c',2 union all
select 'c',3 union all
select 'c',5 union all
select 'd',2 union all
select 'd',3 union all
select 'd',4 union all
select 'd',5
go
select username from test group by username having max(id)-min(id)<>count(*)-1
go
/*
username
----------
b
c
(2 行受影响)
*/
select
username
from
test a left join test b
on
a.[username]=b.[username]
where
a.id=b.id-1
and
exists(select 1 from test where username=a.username and id<>a.id)
and
a.username is not null
use Tempdb
go
--> -->
if not object_id(N'Tempdb..#test') is null
drop table #test
Go
Create table #test([username] nvarchar(1),[id] int)
Insert #test
select N'a',1 union all
select N'a',2 union all
select N'a',3 union all
select N'b',1 union all
select N'b',3 union all
select N'b',4 union all
select N'c',1 union all
select N'c',2 union all
select N'c',3 union all
select N'c',5 union all
select N'd',2 union all
select N'd',3 union all
select N'd',4 union all
select N'd',5
Go
Select [username]
from #test AS a
WHERE NOT EXISTS(SELECT 1 FROM #test WHERE [username]=a.[username] AND ID=a.ID+1)
GROUP BY [username]
HAVING COUNT(1)>1
/*
b
c
*/
create table test(username varchar(10),id int)
insert into test select 'a',1
insert into test select 'a',2
insert into test select 'a',3
insert into test select 'b',1
insert into test select 'b',3
insert into test select 'b',4
insert into test select 'c',1
insert into test select 'c',2
insert into test select 'c',3
insert into test select 'c',5
insert into test select 'd',2
insert into test select 'd',3
insert into test select 'd',4
insert into test select 'd',5
go
select username from test a group by username having count(*)<max(id)-min(id)+1
/*
username
----------
b
c
(2 行受影响)
*/
go
drop table test