34,588
社区成员
发帖
与我相关
我的任务
分享
create table #Record
(
aID int identity(1,1),
fID int,
time datetime
)
insert #Record
select 1,'2010-12-10' union all
select 2,'2010-12-11' union all
select 15,'2010-12-13' union all
select 4,'2010-12-14' union all
select 5,'2010-12-15' union all
select 2,'2010-12-16' union all
select 3,'2010-12-17' union all
select 4,'2010-12-18'
go
--要求:查询出离现在最近的5条记录,且fID不重复(没出现在查询出来的记录里面)
--结果:
aID fID time
----------------------------------------
8 4 2010-12-18 00:00:00.000
7 3 2010-12-17 00:00:00.000
6 2 2010-12-16 00:00:00.000
5 5 2010-12-15 00:00:00.000
3 15 2010-12-13 00:00:00.000
create table #Record(aID int identity(1,1),fID int,time datetime)
insert #Record
select 1,'2010-12-10' union all
select 2,'2010-12-11' union all
select 15,'2010-12-13' union all
select 4,'2010-12-14' union all
select 5,'2010-12-15' union all
select 2,'2010-12-16' union all
select 3,'2010-12-17' union all
select 4,'2010-12-18'
SELECT TOP 5 WITH TIES * FROM #Record a
WHERE NOT EXISTS(SELECT 1 FROM #Record WHERE a.fID=fID AND ABS(DATEDIFF(DAY,a.TIME,GETDATE()))
>ABS(DATEDIFF(DAY,TIME,getdate())))
ORDER BY ABS(DATEDIFF(DAY,TIME,getdate()))
DROP TABLE #Record
--result
/*aID fID time
----------- ----------- ------------------------------------------------------
1 1 2010-12-10 00:00:00.000
2 2 2010-12-11 00:00:00.000
3 15 2010-12-13 00:00:00.000
4 4 2010-12-14 00:00:00.000
5 5 2010-12-15 00:00:00.000
(所影响的行数为 5 行)*/
select top 5 * from
(select max(aid) as aid ,fid,max(time)as t from #record group by fid )a order by [t] desc
/*
8 4 2010-12-18 00:00:00.000
7 3 2010-12-17 00:00:00.000
6 2 2010-12-16 00:00:00.000
5 5 2010-12-15 00:00:00.000
3 15 2010-12-13 00:00:00.000
*/
这是我写的语句,但是没成功,注意要求:...,且fID不重复(没出现在查询出来的记录里面)
select top(5) * from #Record
order by time desc
select top 5 * From #record a where not exists(select 1 from #record where fID=a.fID and time>a.time) order by time desc
/*
aID fID time
----------------------------------------
8 4 2010-12-18 00:00:00.000
7 3 2010-12-17 00:00:00.000
6 2 2010-12-16 00:00:00.000
5 5 2010-12-15 00:00:00.000
3 15 2010-12-13 00:00:00.000
*/
select top 5 *
from tb
order by [time] desc