Forum Discussion

czaldumbide's avatar
czaldumbide
Icon for Helper II rankHelper II
6 years ago
Solved

calculating sum for max date

I created a matrix with the product name as rows, and the sum of amount for the latest purchase date as the value.    I am using the following measure for my value:  CALCULATE(SUM('Sales'[Amount])...
  • AlB's avatar
    6 years ago

    Hi czaldumbide 

    The MAX() in your measure will give you the latest date for the product in that row, since products is part of the filter context. Try this:

    Measure =
    VAR latestdate_ =
        MAX ( ALL ( 'Sales'[Date] ) )
    RETURN
        CALCULATE (
            SUM ( 'Sales'[Amount] ),
            FILTER ( 'Sales', 'Sales'[Date] = latestdate_ )
        )

     Please mark the question solved when done and consider giving kudos if posts are helpful.

    Contact me privately for support with any larger-scale BI needs

    Cheers 

  • Anonymous's avatar
    Anonymous
    6 years ago

    There are several things wrong with your code.

     

    First, you are creating a filter out of the whole expanded fact table. THIS IS VERY, VERY BAD and slows down calculations tremendously. If you start doing such calculations on big fact tables, you'll feel the heat instantly. One of the golden rules of DAX programming says: Never filter a table if you can filter a column.

     

    Secondly, you should have a Calendar dimension in your model.

     

    If you do have a proper Calendar, then you can write:

    [Latest Sales Amount] =
    var __latestSalesDate =
    	CALCULATE(
    		// This is the very latest
    		// day with any sales in it
    		// with no regard to any
    		// selections in any slicers.
    		MAX( Sales[Date] ),
    		ALL( Sales )
    	)
    var __result = 
    	CALCULATE(
    		SUM( Sales[Amount] ),
    		// This only works correctly
    		// if Calendar is THE date table
    		// in the model.
    		Calendar[Date] = __latestSalesDate
    	)
    return
    	__result


    Best
    D