Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
5 years ago
Solved

How to sort column with mixed data type

I have a column containing positive and negative numbers as well as text values. It is a result of calulation, where sometime data are missing or the calculation makes no sense. e.g.:  10 -1 No D...
  • edhans's avatar
    edhans
    5 years ago

    You cannot have text and values in the same column in Power BI unless you leave the data as "any" or untyped, and that still gets all converted to the DAX model as text, so it will sort as text.

    What you could do is sort it as desired in Power Query, then add an index column, then in Power BI, Sort your main column by the index column.

    In the above image, I sorted the data which was the ANY type (ABC/123) then added an index column, then converted the original column explicitly to text. It is bad practice to leave any untyped columns in Power Query tables you load to the model.

     

    See this M code:

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlSK1YlWMgKTiWBS10QpNhYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
        #"Added Custom" = Table.AddColumn(Source, "Custom", each try Number.From([Column1]) otherwise [Column1]),
        #"Sorted Rows" = Table.Sort(#"Added Custom",{{"Custom", Order.Ascending}}),
        #"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 0, 1, Int64.Type),
        #"Changed Type" = Table.TransformColumnTypes(#"Added Index",{{"Custom", type text}}),
        #"Removed Other Columns" = Table.SelectColumns(#"Changed Type",{"Custom", "Index"})
    in
        #"Removed Other Columns"

     

     

    So 

    would sort like this:

    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.

     

    For more on the Sort By Column, see Sort by column in Power BI Desktop - Power BI | Microsoft Docs