test表中有两个字段,id int 自增及No varchar(10)。如连续的id如(id:2,3,4)对应的No都是一样的,则只取第一条即(id为2的那一条)。
create table test
(
id int identity(1,1),
No varchar(10)
)
insert test values('1'),('2'),('2').('2'),('3'),('3'),('1')
要得到的结果:
id No
1 1
2 2
5 3
7 1
select a.id,a.No from test a left join test b on a.id+1=b.id and a.No=b.No where b.id is null
利用一表两用,使得互邻的两条数据进行比较,left join之后 b.id 为null值表示对应的a表中数据第一次出现。
select * from test as a where not exists (select * from test as b where a.id=b.id-1 and a.No=b.No) order by a.id
posted on
浙公网安备 33010602011771号