Code Generator | Power BI

Power Query M Calculate Average Function

This Power Query M function calculates the average of a specified column in Power BI. It takes the column name and table name as input and returns the average value. Unit tests are included for validation.


Empty image or helper icon

This Query related with thread "Data Analysis & AI Tool Insights"

Prompt

calculates the average

Answer

/*
Function to calculate the average of a column in Power BI
column: Name of the column for which average needs to be calculated
tableName: Name of the table containing the column
Return: Average of the specified column
*/
calculateAverage = (column as text, tableName as text) =>
    let
        averageValue = Table.SelectColumns(tableName, column),
        average = List.Average(averageValue[column])
    in
        average

Example of usage:

calculateAverage("SalesAmount", SalesData)

Unit testing:

let
    result = calculateAverage("SalesAmount", SalesData)
in
    result

The unit test will return the average of the "SalesAmount" column in the "SalesData" table.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This Power Query M function calculates the average of a specified column in Power BI. It takes the column name and table name as input and returns the average value. Unit tests are included for validation.