Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
9 years ago
Solved

time difference between 2 rows

Hi   who can help me?   I have a table like this:   ID | EMPLOYEE | |IN/OUT | Date | Time 1 1002 IN 2017-01-01 08:00 2 ...... 5 1002 OUT 2017-01-01 18:00 6 ...
  • MarcelBeug's avatar
    MarcelBeug
    9 years ago

    In Power Query you can:

    1. Combine Date and Time to DateTime.
    2. Sort on employee and DateTime.
    3. Add 2 indices starting with 0 and 1.
    4. Merge the table with itself using the first and second index as key, so you have the previous values on the same row as the current values.
    5. Add a column with the DateTime minus the previous DateTime if the employee is the same and the previous was IN and the current is OUT, else null.
    6. Sort on ID to restore the original sort (not really necessary).
    7. Remove columns that are no longer needed.
    let
        Source = Table1,
        #"Inserted Merged Date and Time" = Table.AddColumn(Source, "DateTime", each [Date] & [Time], type datetime),
        #"Sorted Rows" = Table.Sort(#"Inserted Merged Date and Time",{{"EMPLOYEE", Order.Ascending}, {"DateTime", Order.Ascending}}),
        #"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 0, 1),
        #"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1),
        #"Merged Queries" = Table.NestedJoin(#"Added Index1",{"Index"},#"Added Index1",{"Index.1"},"Prev",JoinKind.LeftOuter),
        #"Expanded Prev" = Table.ExpandTableColumn(#"Merged Queries", "Prev", {"EMPLOYEE", "IN/OUT", "DateTime"}, {"Prev.EMPLOYEE", "Prev.IN/OUT", "Prev.DateTime"}),
        #"Added Custom" = Table.AddColumn(#"Expanded Prev", "TimeDifference", each if [EMPLOYEE] = [Prev.EMPLOYEE] and [#"Prev.IN/OUT"] = "IN" and [#"IN/OUT"] = "OUT" then [DateTime] - [Prev.DateTime] else null, type nullable duration),
        #"Sorted Rows1" = Table.Sort(#"Added Custom",{{"ID", Order.Ascending}}),
        #"Removed Columns" = Table.RemoveColumns(#"Sorted Rows1",{"DateTime", "Index", "Index.1", "Prev.EMPLOYEE", "Prev.IN/OUT", "Prev.DateTime"})
    in
        #"Removed Columns"