Forum Discussion

jcastr02's avatar
jcastr02
Post Prodigy
5 years ago
Solved

merging columns with rules

How can I merge two columns into new column (col C) where if col A and B are equal then it should only give me the value of what is first column.  If they are not equal then merge two columns together?

 

Col ACol BNew Column  (Col C)
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Example MatchExample MatchExample Match
Muscle Shoals Muscle Shoals
Junuea Junuea
New CityFloridaNew CityFlorida
New CityJupiterNew CityJupiter
New CityJupiterNew CityJupiter
Fort Lauderdale Fort Lauderdale
Miami Miami
  • You could add this as a new calculated column:

    Col C = IF ( [Col A] = [Col B], [Col A], [Col A] & [Col B] )

3 Replies

  • You could add this as a new calculated column:

    Col C = IF ( [Col A] = [Col B], [Col A], [Col A] & [Col B] )

  • edhans's avatar
    edhans
    Community Champion

    jcastr02 

    If you do this in Power Query, you can use this formula in a custom column. You could then remove the other two columns and onlhy bring in the final column to Power BI if you wish.

    if [Col A] = [Col B] then [Col A] 
    else Text.Trim([Col A] & " " & [Col B])

    It generates the 3rd column here:

    Full M code is here:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45Wcq1IzC3ISVXwTSxJzlDSQePH6oyqGKwqfEuLk4ECwRn5iTnFQBVgQa/SvNLURBjPL7VcwTmzpBLId8vJL8pMSUQX9iotyCxJLcIn7JZfVKLgk1iaklqUkpiTCjPbNzMxNxPMiQUA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Col A" = _t, #"Col B" = _t]),
        #"Added New Column" = Table.AddColumn(Source, "New Column", each if [Col A] = [Col B] then [Col A] 
    else Text.Trim([Col A] & " " & [Col B])),
        #"Changed Type" = Table.TransformColumnTypes(#"Added New Column",{{"New Column", type text}})
    in
        #"Changed Type"

     

    How to use M code provided in a blank query:
    1) In Power Query, select New Source, then Blank Query
    2) On the Home ribbon, select "Advanced Editor" button
    3) Remove everything you see, then paste the M code I've given you in that box.
    4) Press Done
    5) See this article if you need help using this M code in your model.