日期:2014-05-17  浏览次数:20423 次

T-sql筛选时间间隔少于20秒的数据
如 有一张表[xiefan]结构如下
id    name    time  (datetime类型)  
1     aaa     2012/11/22 2:35:36
2     bbb     2012/11/22 2:35:41
3     ccc     2012/11/22 2:36:00
4     ddd     2012/11/22 2:36:36
5     eee     2012/11/22 2:36:31
.......
现在想筛选出相邻时间间隔小于20秒的纪录
编写的T-sql语句如下,可执行,但筛选出的信息却是表中所有记录。。。
use GongYi_TouPiao
  DECLARE @a datetime
  DECLARE @b datetime
  DECLARE @n int 
  DECLARE @i int
  SET @i=1
  SET @n=(SELECT count(*) FROM [dbo].[xiefan])
  WHILE @i<=@n
   BEGIN 
      set @a = (SELECT addtime FROM [dbo].[xiefan] WHERE serid=@i)
      set @b = (select addtime from [dbo].[xiefan] where serid=@i+1)
       if(datediff(ss,@a,@b)<=20)
     begin 
      select * into test_t from [dbo].[xiefan] where datediff(ss,@a,@b)<=20
     end
      set @i=@i+1
   END
大家会的请帮帮我
------最佳解决方案--------------------
引用:
能告诉我with   as的作用吗?我学sql没几天,不太懂
1楼的写法叫做CTE,2005以后才出现,但是他这样写仅仅是为了造数据而已,和create talbe 的效果一样。你要留意的是:
select a.*,b.* from tb a,tb b where a.id<b.id and DATEDIFF( second, a.time, b.time)<20 

这句是否满足你的要求
------其他解决方案--------------------

with tb(id,name,time)
as( 
select 1,'aaa','2012/11/22 2:35:36' union all
select 2,'bbb','2012/11/22 2:35:41'union all
select 3 ,'ccc','2012/11/22 2:36:00'union all
select 4 ,'ddd','2012/11/22 2:36:36'union all
select 5 ,'eee','2012/11/22 2:36:31')
select a.*,b.* from tb a,tb b where a.id<b.id and DATEDIFF( second, a.time, b.time)<20


------其他解决方案--------------------
能告诉我with   as的作用吗?我学sql没几天,不太懂
------其他解决方案--------------------
引用:
引用:能告诉我with   as的作用吗?我学sql没几天,不太懂1楼的写法叫做CTE,2005以后才出现,但是他这样写仅仅是为了造数据而已,和create talbe 的效果一样。你要留意的是:
select a.*,b.* from tb a,tb b where a.id<b.id and DATEDIFF( second, ……

a.*  b.*分别表示表a 表b里的所有记录吗?如果a,b在同一个表中该怎么处理?
------其他解决方案--------------------
引用:
引用:
引用:能告诉我with   as的作用吗?我学sql没几天,不太懂1楼的写法叫做CTE,2005以后才出现,但是他这样写仅仅是为了造数据而已,和create talbe 的效果一样。你要留意的是:
select a.*,b.* from tb a,tb b where a.id<b.id and DATEDI……
本来就是一个表,只是自关联来变成两个表而已。