The key to this recipe is the true/false statement for our IF function. The HASONEVALUE function checks to see whether we have a single value for the Item column. If so, we simply return the value from our SUM function. If not, we use the SUMMARIZE function to group our base table in exactly the same manner as our table visualization and then use an analogous iterative aggregator, in this case SUMX, to iteratively aggregate the values in our summarized table.
What this means is that in order to ensure that our measure totals are correct, we must tailor the calculation of the total line to how the measure is used within the context of each visualization. If you are thinking that this severely impacts the self-service aspect of measures, you would be correct.
This recipe has been specifically crafted around performance, and so we start with an IF statement that essentially checks to see whether we should display our measure calculated for a single-row or for a total-row. Because of this structure, we never calculate the summarized table or use the iterative aggregator unless we are in a total row, which happens relatively infrequently within the vast majority of table and matrix visualizations.
Also, it is important to stress that the iterative aggregator used within the total version of our measure must correspond to the aggregation function used within the single-row version of our measure. Thus, if we had used the AVERAGE function in our original Sum measure, we would need to use the corresponding AVERAGEX function in our SumTotal measures.
Finally, you may question why we use two measures, one for single-rows and one that accounts for returning either the single-row aggregate or the total line aggregate versus combining the two measures into a single measure. This can be argued from a variety of perspectives, but the most important aspect is the fact that the single-row version of the measure should stand on its own because it is correct for all instances where a single-row is displayed within a visualization. You may use that measure in a variety of visualizations with different summarizations or groupings of items. Thus, coding best practices dictate that the code should be written on one occasion, versus being written multiple times within multiple measures. In the event that a change is required to the base, a single-row version of the measure, it is best to only have to edit the code once versus searching for all instances of the code within multiple measures.