Forum Discussion
Anonymous
3 years agoNot applicable
Mapping values from the same table recursively
I have the following data, ID From ID Type 1 null a 2 1 b 3 2 c Desired output, ID From ID Type Original Type 1 null a a 2 1 b a 3 2 c a As...
- 3 years ago
Try this:
let Source = Table.TransformColumnTypes(Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUQKiRKVYnWglIyALJJAE5hkDWSCRZKXYWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, #"From ID" = _t, Type = _t]),{{"ID", Int64.Type}, {"From ID", Int64.Type}, {"Type", type text}}), lookup = (n, tbl) => if tbl{[ID=n]}[From ID] = null then tbl{[ID=n]}[Type] else @lookup(tbl{[ID=n]}[From ID], tbl), AddCol = Table.AddColumn(Source, "Original Type", each lookup([ID], Source), type text) in AddColThe key is the recursive function defined in the query:
lookup = (n, tbl) => if tbl{[ID=n]}[From ID] = null then tbl{[ID=n]}[Type] else @lookup(tbl{[ID=n]}[From ID], tbl)Note that you need to use the @ symbol to reference a function from within the definition of that function.
See also:
https://radacad.com/fibonacci-sequence-understanding-the-power-query-recursive-function
AlexisOlson
3 years agoSuper User
Try this:
let
Source = Table.TransformColumnTypes(Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUQKiRKVYnWglIyALJJAE5hkDWSCRZKXYWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, #"From ID" = _t, Type = _t]),{{"ID", Int64.Type}, {"From ID", Int64.Type}, {"Type", type text}}),
lookup = (n, tbl) => if tbl{[ID=n]}[From ID] = null then tbl{[ID=n]}[Type] else @lookup(tbl{[ID=n]}[From ID], tbl),
AddCol = Table.AddColumn(Source, "Original Type", each lookup([ID], Source), type text)
in
AddCol
The key is the recursive function defined in the query:
lookup = (n, tbl) =>
if tbl{[ID=n]}[From ID] = null
then tbl{[ID=n]}[Type]
else @lookup(tbl{[ID=n]}[From ID], tbl)
Note that you need to use the @ symbol to reference a function from within the definition of that function.
See also:
https://radacad.com/fibonacci-sequence-understanding-the-power-query-recursive-function