34,838
社区成员




if object_id('tb') is not null drop table tb
go
create table tb(id int,name varchar(10))
insert tb select 1,'a'
union all select 2,'a'
union all select 3,'a'
union all select 4,'b'
union all select 5,'c'
union all select 6,'c'
union all select 7,'d'
union all select 8,'a'
alter table tb add fid int
declare @i int,@name varchar(10)
update tb
set fid=@i,
@i=case
when name=@name then isnull(@i,0)
else isnull(@i,0)+1
end,
@name=name
select id,name from tb t where not exists(select 1 from tb where name=t.name and fid=t.fid and id<t.id)
/*
id name
----------- ----------
1 a
4 b
5 c
7 d
8 a
(5 行受影响)
*/
alter table tb drop column fid
写的比较麻烦了
-->> Author: 让你望见影子的墙(HEROWANG)生成测试数据 Date:2009-04-18 20:20:24
IF OBJECT_ID('tb') IS NOT NULL
DROP TABLE tb
Go
CREATE TABLE tb(id INT,name NVARCHAR(1))
Go
INSERT INTO tb
SELECT 1,'a' UNION ALL
SELECT 2,'a' UNION ALL
SELECT 3,'a' UNION ALL
SELECT 4,'b' UNION ALL
SELECT 5,'c' UNION ALL
SELECT 6,'c' UNION ALL
SELECT 7,'a' UNION ALL
SELECT 8,'d'
GO
SELECT * FROM TB
select id,name
from (
select *,row=(select count(*)+1 from tb where name=t.name and id<t.id and name=(select name from tb where id=t.id-1))
from tb t)k
where row=1
1 a
4 b
5 c
7 a
8 d
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([col1] int,[col2] varchar(1))
insert [tb]
select 1,'a' union all
select 2,'a' union all
select 3,'a' union all
select 4,'b' union all
select 5,'c' union all
select 6,'c' union all
select 7,'d' union all
select 8,'a'
select
*
from
tb t
where
not exists(select 1 from tb where col2=t.col2 and col1=t.col1-1)
--测试结果:
/*
col1 col2
----------- ----
1 a
4 b
5 c
7 d
8 a
(所影响的行数为 5 行)
*/
select
*
from
tb t
where
not exists(select 1 from tb where col2=t.col2 and col1=t.col1-1)
select * from #a a where col1 in (select min(col1) from #a where col2 = a.col2)
select
min(col1) as col1,
col2
from tb
group by col2
declare @a table (id int,name varchar(10))
insert into @a select 1,'a'
union all select 2,'a'
union all select 3,'a'
union all select 4,'b'
union all select 5,'c'
union all select 6,'c'
union all select 7,'d'
select * from @a a where
not exists (select 1 from @a where id<a.id and name=a.name)
id name
----------- ----------
1 a
4 b
5 c
7 d
(4 行受影响)
select min (id),name
from tb
group by name