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
大家会的请帮帮我
[最优解释]
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没几天,不太懂
[其他解释]
a.* b.*分别表示表a 表b里的所有记录吗?如果a,b在同一个表中该怎么处理?
[其他解释]
本来就是一个表,只是自关联来变成两个表而已。
[其他解释]
结果是查出来了,不过没看懂这种比较的原理。貌似是拿前i~i+k(k值?)条记录与第n条记录比较后,再拿i+1~i
+k+1条记录与第n+1条记录相比较...(有疑问)
因为select的结果有重复记录,能再麻烦你解释下吗? 谢谢
[其他解释]
哪有那么复杂,select a.*,b.* from tb a,tb b where a.id<b.id这个你先查出来看看,理解一下,其实就是错位对比而已。然后再判断datediff
[其他解释]
问题解决了,多谢楼上指教