Home Forums SQL Server 2008 T-SQL (SS2K8) Calculate time difference between two related visitors without using cursor RE: Calculate time difference between two related visitors without using cursor

  • Here are two solutions... The 1st will work in 2008 & 2008R2. The 2nd will work with 2012 and above...

    Note: The full script, including the creation & population of test data is attached as well.

    -- ======================================================================

    -- ======================================================================

    -- 2008 & 2008R2 version --

    IF OBJECT_ID('tempdb..#temp', 'U') IS NOT NULL

    DROP TABLE #temp;

    SELECT

    a.ID,

    a.ArrivalDateTime,

    rn = ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.ArrivalDateTime)

    INTO #temp

    FROM

    #Appointments a;

    SELECT

    t1.ID,

    PrevDate = t2.ArrivalDateTime,

    t1.ArrivalDateTime,

    TimeSincePrevDate = DATEDIFF(hh, t2.ArrivalDateTime, t1.ArrivalDateTime)

    FROM

    #temp t1

    JOIN #temp t2

    ON t1.ID = t2.ID

    AND t1.rn = t2.rn + 1

    WHERE

    DATEDIFF(hh, t2.ArrivalDateTime, t1.ArrivalDateTime) < 72

    ORDER BY

    t1.id,

    t1.ArrivalDateTime;

    -- ======================================================================

    -- ======================================================================

    -- 2012 & up version --

    WITH

    cte_GetPrev AS (

    SELECT

    a.ID,

    PrevDate = LAG(a.ArrivalDateTime, 1) OVER (PARTITION BY a.ID ORDER BY a.ArrivalDateTime),

    a.ArrivalDateTime,

    TimeSincePrevDate = DATEDIFF(hh, LAG(a.ArrivalDateTime, 1) OVER (PARTITION BY a.ID ORDER BY a.ArrivalDateTime), a.ArrivalDateTime)

    FROM

    #Appointments a

    )

    SELECT

    gp.ID,

    gp.PrevDate,

    gp.ArrivalDateTime,

    gp.TimeSincePrevDate

    FROM

    cte_GetPrev gp

    WHERE

    gp.TimeSincePrevDate < 72;