62,272
社区成员
发帖
与我相关
我的任务
分享
create table #t
(
id int not null identity(1,1) primary key,
a varchar(20) not null,
b varchar(20) not null
)
insert #t
values
('nnn','855'),
('nnn','986'),
('eee','123'),
('rrr','485'),
('eee','598'),
('ttt','625'),
('eee','256'),
('rrr','186')
select a,b from #t
where id in
(
select max(id) from #t
group by a
)
drop table #t
/*
the result is:
nnn 986
ttt 625
eee 256
rrr 186
*/
with temp as
(
select *,row_number() over( order by getdate()) id from test
)
select a,b from temp a where id = (select max(id) from temp where a=a.a )
if object_id('tb')>0
drop table tb
create table tb
(
a varchar(10),
b int
)
go
insert into tb
select 'nnn', 855
union all
select 'nnn', 986
union all
select 'eee', 123
union all
select 'rrr', 485
union all
select 'eee', 598
union all
select 'ttt', 625
union all
select 'eee', 256
union all
select 'rrr', 186
with cte as
(
select row_number() over(order by getdate()) as id,a,b from tb
)
select a.a,a.b
from cte as a
where a.id = (select max(b.id) from cte as b where a.a = b.a group by b.a )
--结果
nnn 986
ttt 625
eee 256
rrr 186
--这是SQL Server2005才有的写法,2000 的话也要自己先构造一个id列。标示你的记录的顺序。
select * from tb a where id = (select max(id) from tb where a=a.a )