Search code examples
sqlsql-serversql-server-2017

Comparing time difference for every other row


I'm trying to determine the length of time in days between using the AR_Event_Creation_Date_Time for every other row. For example, the number of days between the 1 and 2 row, 3rd and 4th, 5th and 6th etc. In other words, there will be a number of days value for every even row and NULL for every odd row. My code below works if there are only two rows per borrower number but falls down when there are more than two. In the results, notice the change in 1002092539

SELECT  Borrower_Number, 
Workgroup_Name,
FORMAT(AR_Event_Creation_Date_Time,'d','en-us') AS Tag_Date,
Usr_Usrnm,
DATEDIFF(day, LAG(AR_Event_Creation_Date_Time,1) OVER(PARTITION BY 
Borrower_Number Order By Borrower_Number), AR_Event_Creation_Date_Time) Diff
FROM Control_Mail

Current and Desired Results. Notice the change in 1002092539


Solution

  • You need to add in a row number. Also your partition by is non-deterministic:

    SELECT  Borrower_Number, 
        Workgroup_Name,
        FORMAT(AR_Event_Creation_Date_Time,'d','en-us') AS Tag_Date,
        Usr_Usrnm,
        DATEDIFF(day, LAG(AR_Event_Creation_Date_Time,1) OVER(PARTITION BY Borrower_Number, (rn - 1) / 2 ORDER BY AR_Event_Creation_Date_Time),
        AR_Event_Creation_Date_Time) Diff
    FROM (
        SELECT *,
        ROW_NUMBER() OVER (PARTITION BY Borrower_Number ORDER BY AR_Event_Creation_Date_Time) AS rn
        FROM Control_Mail
    ) C
    ```