Search code examples
azure-data-explorerkql

Time difference between separate rows in same table


I have Sessions table

Sessions
|Timespan|Name |No|
|12:00:00|Start|1 |
|12:01:00|End  |2 |
|12:02:00|Start|3 |
|12:04:00|Start|4 |
|12:04:30|Error|5 |

I need to extract from it duration of each session using KQL (but if you could give me suggestion how I can do it with some other query language it would be also very helpful). But if next row after start is also start, it means session was abandoned and we should ignore it.

Expected result:

|Duration|SessionNo|
|00:01:00|    1    |
|00:00:30|    4    |

Solution

  • You can try something like this:

    Sessions
    | order by No asc 
    | extend nextName = next(Name), nextTimestamp = next(timestamp)
    | where Name == "Start" and nextName != "Start"
    | project Duration = nextTimestamp - timestamp, No
    

    When using the operator order by, you are getting a Serialized row set, which then you can use operators such as next and prev. Basically you are seeking rows with No == "Start" and next(Name) == "End", so this is what I did,

    You can find this query running at Kusto Samples open database.