22,210
社区成员
发帖
与我相关
我的任务
分享
;with TT
as(select ROW_NUMBER() over(PARTITION by 类型 order by 时间 desc )as nn ,* from TB)
select ID,类型,时间 from TT where nn = 1
select A.* from (select 类型,max(时间),其它 from table group by 类型,其它)b join a on a.类型=b.类型 and a.时间=b.时间 and a.其它=b.其它
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (ID int,类型 nvarchar(2),时间 datetime,其它 sql_variant)
insert into [TB]
select 1,'A','2012-04-23 18:00:00',null union all
select 2,'A','2012-04-24 18:00:00',null union all
select 3,'A','2012-04-25 18:00:00',null union all
select 5,'B','2012-04-23 18:00:00',null union all
select 6,'B','2012-04-24 18:00:00',null union all
select 7,'C','2012-04-25 18:00:00',null union all
select 8,'C','2012-04-23 18:00:00',null
select * from [TB]
select distinct B.ID,B.类型,B.时间
from TB A
cross apply(select top 1 ID,类型,时间 from TB where 类型 = A.类型 order by 时间 desc) B
/*
3 A 2012-04-25 18:00:00.000
6 B 2012-04-24 18:00:00.000
7 C 2012-04-25 18:00:00.000*/
select 类型,
时间
from 表 t
where id in(select top 1 id from 表 where 类型=t.类型 order by 时间 desc)