Forum Discussion

DMT_corp's avatar
DMT_corp
Regular Visitor
3 years ago

Return a one for the first instance of duplicate values and a “zero” for the other instances

I have a index column, Id customer column . In id customer have a lot of duplicates. And i want  Return a one for the first instance of duplicate values and a “zero” for the other instances

3 Replies

    • Add an Index column to be able to sort back to original order
    • Group by Customer ID
    • Within each subgroup:
      • Add another index column to mark the first duplicate
      • Transform that Index column so the 2nd row (first duplicate) is a 1 and other entries are 0's
    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSlSK1YlWSgKTyWAyEYlMwpCFkClIZCoSmQYm05ViYwE=", 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 text}}),
    
    //add index column to be able to sort back to original order
        #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1, Int64.Type),
    
    //Group by the ID column (Column1 here)
    //then add a column to each subgroup which has a one for the first duplicate entry (2nd entry) in each sub-table
        #"Grouped Rows" = Table.Group(#"Added Index", {"Column1"}, {
            {"First Duplicate", (t)=>
                Table.TransformColumns(
                    Table.AddIndexColumn(t,"First Duplicate",0,1,Int64.Type),
                    {"First Duplicate", each if _ = 1 then 1 else 0})}
                }),
    
    //re-expand and sort back to original order
        #"Expanded First Duplicate" = Table.ExpandTableColumn(#"Grouped Rows", "First Duplicate", {"Index", "First Duplicate"}),
        #"Sorted Rows" = Table.Sort(#"Expanded First Duplicate",{{"Index", Order.Ascending}}),
        #"Removed Columns" = Table.RemoveColumns(#"Sorted Rows",{"Index"})
    in
        #"Removed Columns"

     

    If you want to mark the very first entry as a 1 (if there are duplicates), you can change that line in the Table.Group aggregation to mark the first entry if Table.RowCount is > 1

    • DMT_corp's avatar
      DMT_corp
      Regular Visitor

      Really, i don't understand its

       

      • ronrsnfld's avatar
        ronrsnfld
        Icon for Super User rankSuper User

        Be specific. This is not the place for a tutorial in Power Query, so what, specifically, do you not understand?