简体   繁体   English

在SQL Server的特定列中查找每一行之间的时差

[英]Finding time differences between each row in a specific column in SQL Server

Still learning SQL, but I'm trying to see if there are any Customers that have a time frame within 24 hours of each other. 仍在学习SQL,但是我试图查看是否有任何客户的时间间隔在24小时之内。 So in this example ID 1 and 4 meet this criteria. 因此,在此示例中,ID 1和4满足此条件。

CustID Date
1   2018-04-10 11:21:00.000
1   2018-03-05 18:14:00.000
1   2018-03-05 22:53:00.000
2   2018-04-10 11:21:00.000
2   2018-03-27 14:57:00.000
2   2018-04-04 20:00:00.000
3   2018-04-10 11:21:00.000
3   2018-02-10 11:21:00.000
3   2018-04-24 11:29:00.000
4   2018-04-10 11:21:00.000
4   2018-04-10 11:20:00.000
4   2018-04-24 11:29:00.000

I'm thinking about doing something like 我正在考虑做类似的事情

 SELECT CustId
    From Cars c 
    CROSS APPLY(
    SELECT Date 
    FROM Cars 
    Where Date != c.Date)
WHERE Date - c.Date < 24 hours

Use lag() : 使用lag()

select distinct custid
from (select c.*,
             lag(c.date) over (partition by c.custid order by c.date) as prev_date
      from cars c
     ) c
where date < dateadd(hour, 24, prev_date);

This answer is based on sql-server, but you should be able to translate as needed. 该答案基于sql-server,但是您应该能够根据需要进行翻译。 I also assumed you had a requirement where the same datetime between two customers can't be the same. 我还假设您有一个要求,即两个客户之间的相同日期时间不能相同。 If that's a false assumption, remove the where clause. 如果这是一个错误的假设,请删除where子句。 A simple self-join should get you there. 一个简单的自我加入应该可以帮助您实现目标。

declare @t table (id int, dt datetime)

insert into @t values ('1','2018-04-10 11:21:00.000')
insert into @t values ('1','2018-03-05 18:14:00.000')
insert into @t values ('1','2018-03-05 22:53:00.000')
insert into @t values ('2','2018-04-10 11:21:00.000')
insert into @t values ('2','2018-03-27 14:57:00.000')
insert into @t values ('2','2018-04-04 20:00:00.000')
insert into @t values ('3','2018-04-10 11:21:00.000')
insert into @t values ('3','2018-02-10 11:21:00.000')
insert into @t values ('3','2018-04-24 11:29:00.000')
insert into @t values ('4','2018-04-10 11:21:00.000')
insert into @t values ('4','2018-04-10 11:20:00.000')
insert into @t values ('4','2018-04-24 11:29:00.000')

select
 t1.id, t2.id
from @t t1
join @t t2 on t2.dt between dateadd(hh, -24,t1.dt) and t1.dt and t1.id<>t2.id
where t1.dt<>t2.dt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM