Forum Discussion
atpostdata
3 years agoFrequent Visitor
How to get top5 values based on a field.
To retrieve the top 5 values from each category based on a specific field in Power BI, I used below measure but it giving me all negative records. Top5Negative Records =
CALCULATE(...
- 3 years ago
msahari
1 year agoFrequent Visitor
Let's work on getting the desired output where all tied values are included when calculating the top 5 records based on the values field.
Here's how you can achieve this in M Query:
Load Your Data Source:
- Open Power Query and load your data source.
Sort the Table:
- Sort the table by the values column in descending order.
Identify the Top 5 Values:
- Identify the unique top 5 values.
Filter the Table:
- Filter the table to include all rows where the values column matches any of the top 5 values.
Here's a sample M Query script to achieve this:
let
// Step 1: Load your data source
Source = Excel.Workbook(File.Contents("YourFilePath.xlsx"), null, true),
Data = Source{[Name="YourSheetName"]}[Data],
// Step 2: Sort the table by the "values" column in descending order
SortedTable = Table.Sort(Data, {{"values", Order.Descending}}),
// Step 3: Identify the unique top 5 values
Top5Values = List.FirstN(List.Distinct(List.Sort(Table.Column(SortedTable, "values"), Order.Descending)), 5),
// Step 4: Filter the table to include all rows with the top 5 values
FilteredTable = Table.SelectRows(SortedTable, each List.Contains(Top5Values, [values]))
in
FilteredTableReplace "YourFilePath.xlsx" and "YourSheetName" with your actual file path and sheet name. This script will sort the table by the values column, identify the unique top 5 values, and filter the table to include all rows with those values.