Forum Discussion

RichOB's avatar
RichOB
Icon for Post Partisan rankPost Partisan
1 year ago
Solved

Measure for highest reason per month

Hi, using the table below, how can I get the highest Reason_Ended by month shown in the lower table, please?   End_Date Customer Reason_Ended 01/04/2024 1 Too Expensive 01/04/2024 2 ...
  • v-sathmakuri's avatar
    1 year ago

    Hi RichOB ,

     

    Thank you for reaching out to Microsoft Fabric Community.

     

    Thank you johnt75  and bhanu_gautam  for the prompt response.

     

    first group the data by End_Date and Reason_Ended and get the count of rows and then apply rank for the result based on count for each month. once we got the count filter the data which is having the rank as 1. This will give your expected result. I have used power query to do this. Also attached pbix file for reference.

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjDUNTDRNTIwMlHSUTIE4pD8fAXXioLUvOLMslSlWB00JUaElRgDsUdiUYpCSL5CaDEWBSY4zTCFKTEFYs+YUgMDI/OcHAWnVAWnxOTsQwswFZoRq9CcsKUWOBwOV2BJwDIzeEAa4DAKoQJ3WCPUGBE0BVdYm8NV4A5shBpTItQQCmiESnOiVVoQYa8lpppYAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [End_Date = _t, Customer = _t, Reason_Ended = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"End_Date", type date}, {"Customer", Int64.Type}, {"Reason_Ended", type text}}),
        
        // Group by End_Date and Reason_Ended, counting rows
        #"Grouped Rows" = Table.Group(#"Changed Type", {"End_Date", "Reason_Ended"}, {{"Count", each Table.RowCount(_), Int64.Type}}),
        
        // Sort by End_Date ascending and Count descending (highest count first)
        #"Sorted" = Table.Sort(#"Grouped Rows", {{"End_Date", Order.Ascending}, {"Count", Order.Descending}}),
        
        // Group by End_Date to get nested tables of reasons per month
        GroupedByMonth = Table.Group(#"Sorted", {"End_Date"}, {{"AllData", each _, type table [End_Date=nullable date, Reason_Ended=nullable text, Count=Int64.Type]}}),
        
        // Add Rank (index starting at 1) in each grouped subtable
        AddRankPerGroup = Table.TransformColumns(
            GroupedByMonth,
            {"AllData", each Table.AddIndexColumn(_, "Rank", 1, 1, Int64.Type)}
        ),
        
        // Expand the grouped tables back into a flat table
        Expanded = Table.ExpandTableColumn(AddRankPerGroup, "AllData", {"Reason_Ended", "Count", "Rank"})
    in
        Expanded

     

    PFBS for expected results: 

     

     

    If this post helps, then please consider Accepting as solution to help the other members find it more quickly, don't forget to give a "Kudos" – I’d truly appreciate it! 

     

    Thank you!!