Code Generator | DAX

DAX CalculateWeightedAverage Function

The DAX CalculateWeightedAverage function computes the weighted average by adding the sum of one column to another and dividing it by the sum of a specified column. It handles BLANK() for invalid inputs.


Empty image or helper icon

Prompt

adds the sum of one column to another and divides it by the sum of another column

Answer

/**
* Function: CalculateWeightedAverage
* Description: This DAX function adds the sum of one column to another and divides it by the sum of another column.
* Parameters:
*   @SumColumn1: The name of the column whose sum needs to be added.
*   @SumColumn2: The name of the column whose sum needs to be divided.
* Returns: The weighted average calculated as the sum of SumColumn1 divided by the sum of SumColumn2.
* Exceptions: Returns BLANK() for invalid inputs.
**/
CalculateWeightedAverage = 
VAR Sum1 = SUM([SumColumn1])
VAR Sum2 = SUM([SumColumn2])
RETURN
IF(ISBLANK(Sum1) || ISBLANK(Sum2) || Sum2 = 0, BLANK(), Sum1 / Sum2)

Usage Example: Suppose we have a table with columns "Revenue", "Cost", and "Quantity". We want to calculate the weighted average of Revenue by dividing the sum of Revenue by the sum of Quantity. To achieve this, we can use the CalculateWeightedAverage function as follows:

WeightedAverageRevenue = CalculateWeightedAverage('Table'[Revenue], 'Table'[Quantity])

This function will return the weighted average of Revenue based on the sum of Revenue and Quantity in the 'Table' 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

The DAX CalculateWeightedAverage function computes the weighted average by adding the sum of one column to another and dividing it by the sum of a specified column. It handles BLANK() for invalid inputs.