查询SQL记录

来源:百度知道 编辑:UC知道 时间:2024/06/22 00:42:26
假设以下:A B 一起去借书,并记录SQL数据库中,表table包括了name 和time(借书的时间),此后他们又去了几次,当然这之间还有其他人去借了书。现在数据库中的数据如下:
id name time
1 A 09/07/01 08:00
2 B 09/07/01 08:01
3 C 09/07/01 08:03
4 D 09/07/02 08:11
5 A 09/07/03 17:01
6 B 09/07/03 17:02
7 D 09/07/03 17:03
从上面数据可以知道,A B借书的时间相差不到3分钟,因此可以判断出他们是一起的(以后还出现了类似情况)
能不能涉及一条SQL语句将这样的结果查出来。即查出 在数据库中,同去借书的人名字(时间间隔为3分钟)。
不是查出3分钟间隔内的所有数据,而是整张表中名字一起出现的情况,判断的依据是他们每次间隔的时间不超过3分钟。 可能要用嵌套。 专家的看不懂。
2楼能帮解释一下语句么Select
*
from @T t
where datediff(mi,[time],(select isnull(min([time]),t.[time]) from @T where [time]>t.[time]))<=3

--> --> (Roy)生成测试数据

declare @T table([id] int,[name] nvarchar(1),[time] Datetime)
Insert @T
select 1,N'A','09/07/01 08:00' union all
select 2,N'B','09/07/01 08:01' union all
select 3,N'C','09/07/01 08:03' union all
select 4,N'D','09/07/02 08:11' union all
select 5,N'A','09/07/03 17:01' union all
select 6,N'B','09/07/03 17:02' union all
select 7,N'D','09/07/03 17:03'

Select
*
from @T t
where datediff(mi,[time],(select isnull(min([time]),t.[time]) from @T where [time]>t.[time]))<=3

select a.name, a.time, b.name, b.time
from table a , table b
where abs(datediff(minute, a.time, b.time))<=3 and a.name<>b.name

注意存在记录的重复情况,比如按同学A来查,能得到同去的B和C,但是按B或C来查,同样会得到同去的A

这个用程序去比较吧