日期:2014-05-19  浏览次数:20572 次

在线等!如何取最接近某一时间的时间?
如:7:41,7:42,7:45
我如何取最接近8:00的7:45这个时间呢,而且7:41,7:42,7:45,都放在一个字段里,
有没有这样的函数?或者其它好的方法?谢谢

------解决方案--------------------
select min(8:00 - datetime) , datetime from tb

min(8:00 - datetime) ,这里具体的写法看你数据库的情况
------解决方案--------------------
try:


create table Test
(
T_date varchar(30)
)

insert Test select '7:41 '
insert Test select '7:42 '
insert Test select '7:45 '


select T_date
from Test T
where T_date =(select top 1 T_date from Test order by datediff(mi, '2000-01-01 8:00:00 ', '2000-01-01 ' + T_date + ':00 ') DESC)

------解决方案--------------------
如果要用 datediff 的话 给它补上 年月日 小时

select top 1 *
from table
order by abs(datediff(s, '1900-1-1 00: '+ '8:00 ' , '1900-1-1 00: '+column1))
------解决方案--------------------
create table test(col varchar(10))
insert test select '7:41 '
union all select '7:42 '
union all select '7:45 '
union all select '8:01 '
go

create function fun(@time varchar(10))
returns table
as
return (select top 1 col from test
order by
abs
(
cast(left(col,charindex( ': ',col)-1) as int)*60
+
cast(right(col,len(col)-charindex( ': ',col)) as int)
)
-
(
cast(left(@time,charindex( ': ',@time)-1) as int)*60
+
cast(right(@time,len(@time)-charindex( ': ',@time)) as int)
) desc)
go


select * from dbo.fun( '8:00 ')

drop function fun
drop table test

--8:01