Hi @Naila,
Think I’ve got this sored, try this (copy the full script into a new blank query)
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCkstys9T8MmvKMnPU4rViVZyzMvLTFUIyi8uBnPdE4sqFYIqEyGSIRmpCq7FJYklqQr5aQq+RcUKYP2JyAagqnFEMQ1dvwKS8bEA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Name = _t]),
AddRecord = Table.AddColumn(Source, "Record", each
[
Prefix = let strings = List.Transform( Text.Split([Name], " "), each Text.Proper(_) & " ") in if List.ContainsAny( strings, { "Mr ", "Mr. " }) then "Mr" else if List.ContainsAny( strings, { "Mrs ", "Mrs. " }) then "Mrs" else "",
Estate = if Text.Contains([Name], "The Estate of", Comparer.OrdinalIgnoreCase) then "The Estate of " else null,
Name only = if (Text.Contains([Name], "The Estate of", Comparer.OrdinalIgnoreCase) and Text.Length( Prefix) <> 0 ) then Text.Trim(Text.Range([Name], 17 )) else if (Text.Contains([Name], "The Estate of", Comparer.OrdinalIgnoreCase) and Text.Length( Prefix ) = 0 ) then Text.Range([Name], 14 ) else [Name]
] ),
SortRows = Table.Buffer( Table.Sort( Table.ExpandRecordColumn( AddRecord, "Record", {"Prefix", "Estate", "Name only"}), {{"Name only", Order.Ascending}, {"Prefix", Order.Descending}})),
GroupAndTransformRows = Table.Group(SortRows, {"Name only"}, {{"AllRows", each Table.FillDown( Table.FromColumns( {_[Name], List.ReplaceMatchingItems( _[Prefix], {{"", null}})}, {"Name", "Prefix"}), {"Prefix"}), type table }}),
CombineStrings = Table.AddColumn( Table.ExpandTableColumn(GroupAndTransformRows, "AllRows", {"Name", "Prefix"}, {"Name", "Prefix"}), "Custom", each Text.Combine( {"The Estate of", [Prefix], [Name only] }, " "), type text)[[Name], [Custom]]
in
CombineStrings
.
Note that some names don’t match but when you fix the type-o’s it will return the desired result.
I hope this is helpful