web analytics

How to calculate time differences between adjacent rows in SQL?

Options

codeling 1595 - 6639
@2016-02-04 23:38:50

I have a table named log_table which is used to store all logs produced by an application, see sample records below:

log_ts				message
2016/02/03 4:32:32.297454 PM 	log message1
2016/02/03 4:32:32.298104 PM 	log message2
2016/02/03 4:32:37.642949 PM 	log message3
2016/02/03 5:31:08.347527 PM 	log message4
2016/02/03 5:31:08.404844 PM 	log message5
2016/02/03 5:31:10.146926 PM 	log message6
2016/02/03 5:31:15.149461 PM 	log message7
2016/02/03 5:31:15.510562 PM 	log message8
2016/02/03 5:31:15.665824 PM 	log message9
2016/02/03 5:31:15.674948 PM 	log message10

How can I calculate the time difference between the row and the previous row using just SQL?

@2016-02-05 00:01:55

Solution

The following SQL statement will produce the expected results:

WITH    wlog AS
        (
        SELECT log.*,  ROW_NUMBER() OVER (ORDER BY log_ts ) AS rn
        FROM    log_table log
        )
SELECT log2.log_ts, log1.log_ts,  (log2.log_ts - log1.log_ts)
FROM    wlog log1
inner JOIN    wlog log2
ON      log1.rn = log2.rn - 1

The results are:

2016/02/03 4:32:32.298104 PM  2016/02/03 4:32:32.297454 PM  +000000000 00:00:00.000650
2016/02/03 4:32:37.642949 PM  2016/02/03 4:32:32.298104 PM  +000000000 00:00:05.344845
2016/02/03 5:31:08.347527 PM  2016/02/03 4:32:37.642949 PM  +000000000 00:58:30.704578
2016/02/03 5:31:08.404844 PM  2016/02/03 5:31:08.347527 PM  +000000000 00:00:00.057317
2016/02/03 5:31:10.146926 PM  2016/02/03 5:31:08.404844 PM  +000000000 00:00:01.742082
2016/02/03 5:31:15.149461 PM  2016/02/03 5:31:10.146926 PM  +000000000 00:00:05.002535
2016/02/03 5:31:15.510562 PM  2016/02/03 5:31:15.149461 PM  +000000000 00:00:00.361101
2016/02/03 5:31:15.665824 PM  2016/02/03 5:31:15.510562 PM  +000000000 00:00:00.155262
2016/02/03 5:31:15.674948 PM  2016/02/03 5:31:15.665824 PM  +000000000 00:00:00.009124

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com