Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
6 years ago
Solved

Add end date to row

Hello,   I hope you can help me with the following question:   I have a table who has only a start date. The end date of the production is the next start date of the production of the group custo...
  • Anonymous's avatar
    Anonymous
    6 years ago

    The attached code is an alternate method that presumes you are using Excel Power Query. You can change the source to adapt to your data. The function OffsetCol is an inline function that efficiently gets the next row. A custom column is then used to detect if the Customer and Contract changes.

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Data"]}[Content],
        //(Source as table, ColName as text, optional offset as  number) =>
    OffsetCol = (   Source as table,  RecordColumnName as text, optional Columns as list, optional  offset as number   ) =>
    let
         offset = if offset = null then -1 else offset,
        // Prefix = if prefix = null then "Prior" else prefix,
       Columns = List.Buffer(if Columns = null then Table.ColumnNames(Source) else Columns), 
    
         SourceSelect = if Columns = null then Source else Table.SelectColumns(Source,Columns),
    
         ShiftedList = if offset < 0 then List.Repeat({null}, -offset)  &  List.RemoveLastN(Table.ToRecords(SourceSelect ),-offset)
                    else List.RemoveFirstN(Table.ToRecords(SourceSelect ),offset) &  List.Repeat({null}, offset),
        
        Combine1 = Table.ToColumns(Source) & {ShiftedList},
        Combine2     = Table.FromColumns(Combine1, Table.ColumnNames(Source) & {RecordColumnName} )
     in
        Combine2,
        Result = OffsetCol(Source, "NextRecord", {"Start Date", "Customer","Contract"},1),
        #"Added Custom" = Table.AddColumn(Result, "EndDate", each if [NextRecord]=  null or [NextRecord][Contract] <> [Contract] or [NextRecord][Customer] <> [Customer] then  null else [NextRecord][Start Date]),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"NextRecord"})
    in
        #"Removed Columns"