create table a(日期 varchar(10), 号码1 varchar(10), 号码2 varchar(10), 序号 int)
insert into a values('20060101' , 'A1' , 'B1' , 3 )
insert into a values('20060101' , 'A1' , 'B1' , 4 )
insert into a values('20060101' , 'A1' , 'B1' , 2 )
insert into a values('20060105' , 'C1' , 'D1' , 2 )
insert into a values('20070101' , 'A1' , 'B1' , 1 )
goselect 日期 ,
号码1,
号码2,
max(序号) 序号
from a
group by 日期 , 号码1 , 号码2drop table a/*日期 号码1 号码2 序号
---------- ---------- ---------- -----------
20060101 A1 B1 4
20060105 C1 D1 2
20070101 A1 B1 1(所影响的行数为 3 行)
*/
insert into a values('20060101' , 'A1' , 'B1' , 3 )
insert into a values('20060101' , 'A1' , 'B1' , 4 )
insert into a values('20060101' , 'A1' , 'B1' , 2 )
insert into a values('20060105' , 'C1' , 'D1' , 2 )
insert into a values('20070101' , 'A1' , 'B1' , 1 )
goselect 日期 ,
号码1,
号码2,
max(序号) 序号
from a
group by 日期 , 号码1 , 号码2drop table a/*日期 号码1 号码2 序号
---------- ---------- ---------- -----------
20060101 A1 B1 4
20060105 C1 D1 2
20070101 A1 B1 1(所影响的行数为 3 行)
*/
insert into a values('20060101' , 'A1' , 'B1' , 3 ,'Y')
insert into a values('20060101' , 'A1' , 'B1' , 4 ,'N')
insert into a values('20060101' , 'A1' , 'B1' , 2 ,'Y')
insert into a values('20060105' , 'C1' , 'D1' , 2 ,'N')
insert into a values('20070101' , 'A1' , 'B1' , 1 ,'Y')
go--1
select t.* from a t where 序号 = (select max(序号) from a where 日期 = t.日期 and 号码1 = t.号码1 and 号码2 = t.号码2)--2
select t.* from a t where not exists (select 1 from a where 日期 = t.日期 and 号码1 = t.号码1 and 号码2 = t.号码2 and 序号 > t.序号)drop table a/*日期 号码1 号码2 序号 标记
---------- ---------- ---------- ----------- ----------
20070101 A1 B1 1 Y
20060105 C1 D1 2 N
20060101 A1 B1 4 N(所影响的行数为 3 行)
*/
declare @a table(日期 varchar(10), 号码1 varchar(10), 号码2 varchar(10), 序号 int, 标记 varchar(4))
insert into @a values('20060101' , 'A1' , 'B1' , 3 ,'Y')
insert into @a values('20060101' , 'A1' , 'B1' , 4 ,'N')
insert into @a values('20060101' , 'A1' , 'B1' , 2 ,'Y')
insert into @a values('20060105' , 'C1' , 'D1' , 2 ,'N')
insert into @a values('20070101' , 'A1' , 'B1' , 1 ,'Y')select t.* from @A t where not exists(select 1 from @A where 日期=t.日期 and 号码1=t.号码1 and 号码2=t.号码2 and 序号>t.序号)
/*
日期 号码1 号码2 序号 标记
---------- ---------- ---------- ----------- ----
20060101 A1 B1 4 N
20060105 C1 D1 2 N
20070101 A1 B1 1 Y
*/select t.* from @A t where 序号=(select max(序号) from @A where 日期=t.日期 and 号码1=t.号码1 and 号码2=t.号码2)
/*
日期 号码1 号码2 序号 标记
---------- ---------- ---------- ----------- ----
20060101 A1 B1 4 N
20060105 C1 D1 2 N
20070101 A1 B1 1 Y
*/