日期:2014-05-18  浏览次数:20437 次

请帮忙写一条关于时间的语句
内容:两张表
A表:
时间字段:2007.09.22


B表:也是时间字段,如果有5条记录:
2007.01.01
2007.02.02
2007.03.03
2007.04.04
2007.05.05

需求:
以A表的时间记录为条件,在B表找出离A表的时间紧近的一条记录。
结果应该是:2007.05.05这一条。请问语句如何写?


------解决方案--------------------
占上就有了

------解决方案--------------------
select top 1 * from 表B order by abs(时间字段-(select max(时间字段) from A表))
------解决方案--------------------


select max(t1.时间字段) from B t1 left join A t2 on t1.關鍵字=t2.關鍵字
where t1.时间字段 < t2.时间字段
group by t1.關鍵字
------解决方案--------------------

declare @a table(name1 datetime)
insert @a
select '2007.09.01 '

declare @b table(name2 datetime)
insert @b
select '2007.01.01 '
union all
select '2007.02.02 '
union all
select '2007.03.03 '
union all
select '2007.04.04 '
union all
select '2007.05.05 '


select top 1 name2 from @b b,@a a order by datediff(day,name2,name1)

/*

(所影响的行数为 1 行)


(所影响的行数为 5 行)

name2
------------------------------------------------------
2007-01-01 00:00:00.000

(所影响的行数为 1 行)
*/