sql server 2012 - Time difference between two rows for specified ID -
i'm trying find time difference in seconds between 2 rows have same id. here's simple table. the table ordered myid , timestamp . i'm trying total second between 2 rows have same myid . here's have come with. problem query calculates time difference records not same id. select datediff(second, ptimestamp, timestamp), q.* ( select *, lag(timestamp) on (order timestamp) ptimestamp data ) q ptimestamp not null this output. i want output highlighted in yellow. any suggestions? sqlfiddle the fix matter of narrowing window, partition by , rows same id : select datediff(second, ptimestamp, timestamp), q.* ( select *, lag(timestamp) on (partition id order timestamp) ptimestamp data ) q ptimestamp not null