用于计算天差的SQL查询

时间:2016-03-10 15:13:03

标签: sql-server sql-server-2012

我有一张如下表:

ID    Level    Date      Days difference

123    B       1/6/2014      ------
123    A       5/16/2014     ------ 
123    B       9/21/2014     ------
123    B       12/19/2014    ------
123    B       3/17/2015     305
123    A       4/5/2015      ------
123    A       8/11/2015     ------ 
123    B       10/12/2015    62

总天数差367

我需要一个SQL查询来获得如上所述的总天数差异。它应该是A最接近A的减去日期之前的B的最后日期。

1 个答案:

答案 0 :(得分:0)

您可以将case语句与lag / lead一起使用以获得正确的结果:

CREATE TABLE #tmp
    ([ID] int, [Level] varchar(1), [Date] datetime)
;

INSERT INTO #tmp
    ([ID], [Level], [Date])
VALUES
    (123, 'B', '2014-01-06 02:00:00'),
    (123, 'A', '2014-05-16 03:00:00'),
    (123, 'B', '2014-09-21 03:00:00'),
    (123, 'B', '2014-12-19 02:00:00'),
    (123, 'B', '2015-03-17 02:00:00'),
    (123, 'A', '2015-04-05 03:00:00'),
    (123, 'A', '2015-08-11 03:00:00'),
    (123, 'B', '2015-10-12 03:00:00')
;

select *,
datediff(day, case when isnull(lead(Level) over (order by Date asc),'A') = 'A' and Level = 'B' then max(ADate) over (order by Date asc) else NULL end, [Date]) as Diff
from (
  select *, 
    case when lag(Level) over (order by Date desc) = 'B' and Level = 'A' then [Date] else NULL end as ADate
  from #tmp
) X

内部选择将确定从中获取日期的A行,外部查询将确定要计算值的B行+计算它。

Demo