以下是我的数据样本集:
ID DATETIME
1 29-12-2016 03:00
2 28-12-2016 14:00
3 28-12-2016 16:00
4 25-12-2016 00:00预期结果:
ID DATETIME 24HoursDataExisted
1 29-12-2016 03:00 0
2 28-12-2016 14:00 1
3 28-12-2016 16:00 1
4 25-12-2016 00:00 0如何编写这样的查询,对于每条记录,判断在接下来的24小时内是否存在另一条记录?它与DATEADD(hh, 24,datetime)有关,但我不确定如何将其写入SQL。
从上面的示例数据看,由于ID1和ID3的记录,ID2记录为true,而由于ID1记录,ID3为true。
发布于 2016-09-26 17:06:09
如果您使用的是2012,您可以使用lead函数..
select id,datetimee,
case
when datediff(hour,convert(datetime,datetimee,105),cast(lead(convert(datetime,datetimee,105))
over (order by convert(datetime,datetimee,105)) as datetime))<=24
then 1 else 0 end
from #temp
order by id desc对于2008年,您可以使用下面的
;with cte
as
(
select id,convert(datetime,datetimee,105) as dtval,
row_number() over (order by id desc) as rownum
from #temp
)
select c1.id,c1.dtval,
case when datediff(hour,c1.dtval,c2.dtval)<=25 then 1 else 0 end as comecol
from cte c1
left join cte c2
on c1.rownum+1=c2.rownum输出:
id datetimee somecol
4 25-12-2016 00:00 0
3 28-12-2016 16:00 1
2 28-12-2016 14:00 1
1 29-12-2016 15:00 0https://stackoverflow.com/questions/39698487
复制相似问题