Search code examples
daxpowerbi-desktopdaxstudio

How to find TopN for each group in Dax


I would like to find the MAX(FYandFW num) based on each Source.

the sample dataset:

Source  FYandFW num sum
Company A   202453  1
Company A   202452  2
Company A   202451  3
Company B   202501  4
Company B   202502  5
Company B   202453  6

What i am trying is below enter image description here

    Amt = 
VAR i = VALUES('Table'[Source])
VAR j = VALUES('Table'[FYandFW num])
VAR t = 
    TOPN(1,
    CALCULATETABLE('Table', REMOVEFILTERS(), i),
    'Table'[FYandFW num], DESC) 


RETURN
    CALCULATE(SUM('Table'[sum]),t , j)

Expected Answer is Amt = 5 + 1


Solution

  • Try this approach:

    Amt = 
      var tSourceMax = 
        SUMMARIZE(
          ALL('Table'),
          'Table'[Source],
          "MaxFYFW", MAX('Table'[FYandFW num])
        )
      RETURN
        SUMX(
          'Table',
          CALCULATE(
            MAX('Table'[sum]),
            FILTER(tSourceMax, 'Table'[Source] = [Source] && 'Table'[FYandFW num] = [MaxFYFW])
          )
        )
    

    enter image description here