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

时间:2018-06-05 19:29:08

标签: sql sql-server

仍然在学习SQL,但我正在尝试查看是否有任何客户在24小时内拥有时间框架。因此,在此示例中,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

我正在考虑做类似

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

2 个答案:

答案 0 :(得分:2)

使用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);

答案 1 :(得分:1)

此答案基于sql-server,但您应该能够根据需要进行翻译。我还假设您有一个要求,即两个客户之间的相同日期时间可以相同。如果这是错误的假设,请删除where子句。一个简单的自我加入应该让你到那里。

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