Home > Mobile >  Need Time difference of Current Row Value & Next Row Value in Results
Need Time difference of Current Row Value & Next Row Value in Results

Time:09-19

I need difference between rows of Table. I am getting result but first row coming null so due that the expected results is move in next row. How remove null values from first column of time difference.
Below is my query

SELECT 
    T1.[ID] 
    ,T1.[url_rec] 
    , '' As Diff
    ,record_timestamp
    ,CONVERT(VARCHAR(8),record_timestamp - lag(record_timestamp, 1) OVER (ORDER BY T1.[ID]),108)
FROM (
    SELECT 
        [ID] 
        ,[url_rec] 
        ,[record_timestamp]
        ,ROW_NUMBER() OVER (ORDER BY [ID]) AS 'RowNum'
        
    FROM raw_activity_log  T 
) T1 
LEFT JOIN (
    SELECT 
        [ID] 
        ,[url_rec] 
        ,ROW_NUMBER() OVER (ORDER BY [ID]) AS 'RowNum' 
    FROM raw_activity_log T 
) T2 
    ON T2.[RowNum]   1 = T1.[RowNum] 
WHERE T1.[url_rec] <> ISNULL(T2.[url_rec], '') 
ORDER BY T1.[ID]; 
d URL Record_Time Difference
1 https://sabezyessent.teramind.co/#/welcome 2022-05-09 09:44:22.000 NULL
2 https://sabezyessent.teramind.co/#/report/4 2022-05-09 09:47:42.000 00:03:20
3 https://sabezyessent.teramind.co/#/clock 2022-05-09 09:47:37.000 23:59:55
4 https://sabezyessent.teramind.co/#/manage/users/profile/2 2022-05-09 09:47:45.000 00:00:08

Query are written above and result is showing. Why this null values coming I don't know. The values coming in second row that would be first row value. This way every row values showing in next row.

CodePudding user response:

What value do you expect? If you calculate the timedifference between the current row and the previous row, then there is no timedifference for this first row. (there is no row before to have a timediff with.

CodePudding user response:

You can use CURSOR inorder to traverse the above query result as a dynamic query , this might help you compute the time difference between each record and you can update each record with the TIMSDIFFERENCE

follow the link for example : Using a cursor with dynamic SQL in a stored procedure

  • Related