34,593
社区成员
发帖
与我相关
我的任务
分享
DATEADD(day,-1@tima_begin)
为间隔往前推,直到找到同一时刻有记录的那天,并返回a_time
declare @t table(a_time datetime,a_value varchar(1))
Insert @t
select '2008-06-01 01:00:00',N'a' union all
select '2008-06-01 02:00:00',N'b' union all
select '2008-06-01 03:00:00',N'c' union all
select '2008-06-01 04:00:00',N'd' union all
select '2008-06-02 01:00:00',N'e' union all
select '2008-06-02 02:00:00',N'f' union all
select '2008-06-02 03:00:00',N'g' union all
select '2008-06-03 05:00:00',N'w' union all
select '2008-06-03 06:00:00',N'd' union all
select '2008-06-03 07:00:00',N'd' union all
select '2008-06-03 08:00:00',N'd'
select top 1 * from @t
where datepart(hh,a_time)=datepart(hh,cast('2008-06-20 02:00:00' as datetime))
order by a_time desc
2008-06-02 02:00:00.000 f
不用循环吧,通过条件过滤就可以了
declare @t table(a_time varchar(20),a_value varchar(1))
Insert @t
select '2008-06-01 01:00:00',N'a' union all
select '2008-06-01 02:00:00',N'b' union all
select '2008-06-01 03:00:00',N'c' union all
select '2008-06-01 04:00:00',N'd' union all
select '2008-06-02 01:00:00',N'e' union all
select '2008-06-02 02:00:00',N'f' union all
select '2008-06-02 03:00:00',N'g' union all
select '2008-06-03 05:00:00',N'w' union all
select '2008-06-03 06:00:00',N'd' union all
select '2008-06-03 07:00:00',N'd' union all
select '2008-06-03 08:00:00',N'd'
select top 1 * from @t
where charindex(right('2008-06-20 02:00:00',9),a_time)>0
order by a_time desc
2008-06-02 02:00:00 f
DATEADD(day,-1,@tima_begin)
少写个逗号