2016-09-26 33 views
0

下面是我的数据的样本集:如何检查数据并水平显示?

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记录为真,ID1记录导致ID3为真。

回答

0

,如果你使用的是2012年,你可以使用铅功能..

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 0 
+0

你能解释其中'datetimee'来自? – Twinkles

+0

感谢您的回复,但该应用程序仍在SQL Server 2008上运行 –

+0

@ Mr.SuicideSheep:查看2008年更新 – TheGameiswar