22,210
社区成员
发帖
与我相关
我的任务
分享
select top 3 * from #T t where not exists(
select 1 from #T where company=t.company and time>t.time
) order by time desc
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (name varchar(1),type varchar(2),price int,company varchar(1),time datetime)
insert into #T
select 'A','A1',1,'A','2008-7-11 09:16:07' union all
select 'A','A2',2,'A','2008-7-11 09:16:08' union all
select 'B','B1',3,'B','2008-7-11 09:16:02' union all
select 'C','C1',4,'C','2008-7-11 09:16:03' union all
select 'A','A3',5,'A','2008-7-11 09:16:09' union all
select 'D','D1',6,'D','2008-7-11 09:16:10' union all
select 'E','E1',7,'E','2008-7-11 09:16:06'
select top 3 * from (
select * from #T t where not exists(
select 1 from #T where company=t.company and time>t.time
))t order by time desc
select top 3 * from (
select * from 表t t where not exists(
select 1 from 表t where 公司名称=t.公司名称 and 加入时间>t.加入时间
))t order by 加入时间
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (name varchar(1),type varchar(2),price int,company varchar(1),time datetime)
insert into #T
select 'A','A1',1,'A','2008-7-11 09:16:07' union all
select 'A','A2',2,'A','2008-7-11 09:16:08' union all
select 'B','B1',3,'B','2008-7-11 09:16:02' union all
select 'C','C1',4,'C','2008-7-11 09:16:03' union all
select 'A','A3',5,'A','2008-7-11 09:16:09' union all
select 'D','D1',6,'D','2008-7-11 09:16:10' union all
select 'E','E1',7,'E','2008-7-11 09:16:06'
select top 3 a.* from #T as a
inner join
(
select max(time) as time,name from #T group by Name
) as b on a.name=b.name and a.time=b.time order by a.time desc
/*
D D1 6 D 2008-07-11 09:16:10.000
A A3 5 A 2008-07-11 09:16:09.000
E E1 7 E 2008-07-11 09:16:06.000
*/