34,587
社区成员
发帖
与我相关
我的任务
分享
select id,time
from tableName
order by
CASE time>GETDATE()
THEN CONVERT( Float, time)-CONVERT( Float, GETDATE())+CONVERT(FLOAT,'2000-01-01')
ELSE CONVERT( Float, GETDATE())-CONVERT( Float, time)
END
declare @t table(id int,time datetime)
insert @t select
1 ,'2008-12-3' union select
2 ,'2007-11-2' union select
3 ,'2008-10-21' union select
4 ,'2008-5-1' union select
5 ,'2007-7-7'
select * from (select top 100 PERCENT * from @t where time > getdate() order by time) t
union all
select * from (select top 100 PERCENT * from @t where time < getdate() order by time desc) t
/*
id time
----------- ------------------------------------------------------
1 2008-12-03 00:00:00.000
3 2008-10-21 00:00:00.000
4 2008-05-01 00:00:00.000
2 2007-11-02 00:00:00.000
5 2007-07-07 00:00:00.000
(所影响的行数为 5 行)
*/
create table tb(id int, time datetime)
insert into tb values(1, '2008-12-3')
insert into tb values(2, '2007-11-2')
insert into tb values(3, '2008-10-21')
insert into tb values(4, '2008-5-1')
insert into tb values(5, '2007-7-7')
go
select * from (select top 100 * from tb where time > getdate() order by time) t
union all
select * from (select top 100 * from tb where time < getdate() order by time desc) t
drop table tb
/*
id time
----------- ------------------------------------------------------
4 2008-05-01 00:00:00.000
3 2008-10-21 00:00:00.000
1 2008-12-03 00:00:00.000
2 2007-11-02 00:00:00.000
5 2007-07-07 00:00:00.000
(所影响的行数为 5 行)
*/