Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
4 years ago
Solved

How to merge two get nearest previous date by using M Code ?

Hi. I am trying to get nearest previous date from other table(Table1) in Power Query not by DAX?   Table1:   Expected Result : Table2 (added Column1 form Table2):     Any help on ...
  • Vijay_A_Verma's avatar
    4 years ago

    See the working here - Open a blank query - Home - Advanced Editor - Remove everything from there and paste the below code to test

    This code is for Table2.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjIwMtI1MNQ1NFWK1YFxgQiViyJrDBRB5RoqxcYCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type date}}),
        BuffList = List.Buffer(Table1[Column1]),
        #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each [l=List.Transform(BuffList,(x)=>Duration.Days(x-[Column1])),p=BuffList{List.PositionOf(l,List.Last(List.Select(l,(y)=>y<=0)))}][p])
    in
        #"Added Custom"

     Code for Table1

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjIwMtI1MAQipVgdGNdI19AAiWsMFFGKjQUA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type date}})
    in
        #"Changed Type"
  • Vijay_A_Verma's avatar
    Vijay_A_Verma
    4 years ago

    You have done in the right manner. As supplying both input and output makes us give right answer.

    You will need to use a try otherwise block

    try [l=List.Transform(BuffList,(x)=>Duration.Days(x-[Column1])),p=BuffList{List.PositionOf(l,List.Last(List.Select(l,(y)=>y<=0)))}][p] otherwise List.Max(BuffList)

    Hence, following code for Table2

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjIwMtI1MNQ1NFWK1YFxgQiViyJrDBRB5RrCuEBzjMDcWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type date}}),
        BuffList = List.Buffer(Table1[Column1]),
        #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each try [l=List.Transform(BuffList,(x)=>Duration.Days(x-[Column1])),p=BuffList{List.PositionOf(l,List.Last(List.Select(l,(y)=>y<=0)))}][p] otherwise List.Max(BuffList))
    in
        #"Added Custom"