在表的同一列中查找日期差异

时间:2016-06-23 21:10:52

标签: sql-server

所以我有一个包含以下示例结构和项目的表。

Type           Date                       ID      Type_Ref
Problem        2015-01-03 02:25:59.360    1002    1
Incident       2015-01-03 06:13:12.125    1003    2
Incident       2015-01-05 00:15:56.700    1004    2
Problem        2015-01-16 13:27:12.325    1005    1
Incident       2015-01-17 15:05:16.703    1006    2
Incident       2015-01-22 18:46:17.986    1007    2
Problem        2015-02-01 09:21:49.123    1008    1

我正在尝试查询,以便在“事件”之间以“天”的形式获得日期之间的最大差异。因此,我想让它查询“事件”列表,然后找出事件记录时间之间的最大差异。所以对于这个表,我正在寻找的查询结果对于事件1004和1006的差异将是12。

有什么想法吗?

为此,我正在使用SQL服务器

2 个答案:

答案 0 :(得分:1)

我从一个通用版本开始,无需过滤或聚合即可完成您的结果。您应该能够以多种方式操纵它:

select a.*
     , DateDiff(day, Lag(a.[Date]) over (partition by a.[Type] order by a.[Date] asc), A.[Date])
from (values
    ('Problem', '2015-01-03 02:25:59.360', 1002)
  , ('Incident', '2015-01-03 06:13:12.125', 1003)
  , ('Incident', '2015-01-05 00:15:56.700', 1004)
  , ('Problem', '2015-01-16 13:27:12.325', 1005)
  , ('Incident', '2015-01-17 15:05:16.703', 1006)
  , ('Incident', '2015-01-22 18:46:17.986', 1007)
  , ('Problem', '2015-02-01 09:21:49.123', 1008)
) as a ([Type], [Date], [Id]);

LAG将根据分区/排序子句找到前一行的值。在示例中,这会导致"之前类型的日期。"您可以详细了解窗口函数here

答案 1 :(得分:0)

我假设日期之间的最大差异,您的意思是“连续日期”。

首先,将其过滤到事件:

select 
  [type],
  [date],
  [id],
  [type_ref]
from problem_log
where [type_ref] = '2' -- or, "where [type] = 'Incident'"
order by [date]

现在使用窗口函数获取日期之间的差异:

select 
  [type],
  [date],
  [id],
  [type_ref],
  datediff(d, lag([date],1) over (order by [date]), [date]) as days_since_last_incident
from problem_log
where [type_ref] = '2' -- or, "where [type] = 'Incident'"
order by [date]

这里是一张桌子:

select * from (
select 
  [type],
  [date],
  [id],
  [type_ref],
  datediff(d, lag([date],1) over (order by [date]), [date]) as days_since_last_incident
from problem_log
where [type_ref] = '2' -- or, "where [type] = 'Incident'"
) sq   
order by [days_since_last_incident] desc`

或将其过滤到我们想要的单个值

select max(days_since_last_incident) as longest_safety_streak from ( 
select 
  [type],
  [date],
  [id],
  [type_ref],
  datediff(d, lag([date],1) over (order by [date]), [date]) as days_since_last_incident
from problem_log
where [type_ref] = '2' -- or, "where [type] = 'Incident'"
) sq