Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
1 year ago

Sub Index Based on Condition from Previous/Next Rows in Power Query

I’m working with a dataset in Power BI and using Power Query to prepare my data for reporting. The dataset tracks multiple trips using the following columns:

  • ShiftID: Represents the time when a truck starts its shift at the depot and returns to the depot.
  • StopType: Either a stop at the Source (S) or Customer (C).
  • StopOrder: Indicates the order of stops in a shift (resets for each new ShiftID).

I need to create a new column in Power Query called TripEvent that increments based on the following rules:

  1. For each ShiftID, the trip event starts at 1, regardless of the first stop (whether it is a Source or a Customer).
  2. The trip event remains the same as long as the truck is stopping at a Customer (StopType = 'C').
  3. If the truck stops at a Source (StopType = 'S'), a new trip event begins, so the trip event number is incremented.
  4. If the last event is a stop at a Source (StopType = 'S') and there are no further deliveries (Customer stops), the trip event remains the same as the previous one (i.e., no increment).

How can I achieve this conditional column logic in Power Query, where the TripEvent column increments and reset based on these conditions?

Thank you in advance for any assistance!

ShiftID   StopOrder  StopType TripEvent
1382883 1 B 1
1382883 2 B 1
1382883 3 B 1
1382883 4 S 1
1383115 1 B 1
1383115 2 B 1
1383115 3 S 1
1383115 4 B 2
1383115 5 S 2
1387288 1 B 1
1387288 2 B 1
1387288 3 S 1
1388995 1 S 1
1388995 2 B 1
1388995 3 B 1
1388995 4 S 1
1390789 1 B 1
1390789 2 B 1
1390789 3 B 1
1390789 4 S 1
1391573 1 S 1
1391573 2 B 1
1391573 3 B 1
1391852 1 B 1
1391852 2 B 1
1391852 3 S 1
1391852 4 B 2
1391852 5 S 2
1395271 1 B 1
1395271 2 S 1
1395271 3 B 2
1395271 4 S 2
1395769 1 B 1
1395769 2 S 1
1395769 3 B 2
1395769 4 S 2
1395997 1 B 1
1395997 2 S 1
1395997 3 B 2
1395997 4 B 2
1395997 5 S 2
1397028 1 B 1
1397028 2 B 1
1397028 3 S 1
1397028 4 B 2
1397028 5 S 2
1398598 1 B 1
1398598 2 S 1
1398598 3 B 2
1398598 4 B 2
1398598 5 S 2
1400647 1 B 1
1400647 2 S 1
1400647 3 B 2
1400647 4 S 2
1400647 5 B 3
1400647 6 B 3
1400647 7 S 3
1477794 1 B 1
1477794 2 S 1
1477794 3 B 2
1477794 4 S 2
1479624 1 B 1
1479624 2 B 1
1479624 3 B 1
1479624 4 S 2
1479624 5 B 2
1479624 6 S 2

2 Replies

  • Anonymous why the last 3 rows in this case is not #2

     

    1388995   1   S   1
    1388995   2   B   1
    1388995   3   B   1
    1388995   4   S   1
    • Anonymous's avatar
      Anonymous
      Not applicable

      Hi, this is my 4th condition
      "If the last event is a stop at a Source (StopType = 'S') and there are no further deliveries (Customer stops), the trip event remains the same as the previous one (i.e., no increment)."

      So this one should stay as 1.