Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
7 years ago
Solved

First X Months per Group

I am looking for a way to keep only the first two (earliest) dates for each grouping in a table like the following. 

 

group date quantity

A1/5/201810
A3/10/20188
A5/12/201815
B2/20/20185
C2/25/201820
C7/19/201828
C10/5/201815

 

So the query would find the first (earliest) two dates for each grouping, and then only keep those rows. the resulting table would look like this:

 

group date quantity

A1/5/201810
A3/10/20188
B2/20/20185
C2/25/201820
C7/19/201828

 

Any thoughts on how to do this with DAX or even M?

  • Anonymous's avatar
    Anonymous
    7 years ago

    I find Power Query to be better to handle this type, of what I call, heavy lifting.  I attached the PBIX below so you can see all the steps, but basically just grouped the data by your Group Column, and then added an index column and used that to create a simple measure.  

     

    Here's the final table from Power Query:

     

    Then all you need is a simple calculate measure:

     

    Quantity Earliest 2 = CALCULATE( SUM ( Table1[Quantity] ), Table1[Index] <= 2)

    which gives you this:

     

     

    For me (and this is just my opinion) that way is much simpler, but to each there own!

     

    PBIX File:

    https://1drv.ms/f/s!AoQIGRpzoxRH8lEXcUUXYVtr5vO2

2 Replies

  • Hi Anonymous

     

    in dax you can do something like:

     

        GENERATE(
            VALUES( Data[Iteam] ),
            CALCULATETABLE(
                TOPN( 
                        2, 
                        SELECTCOLUMNS( Data,  "Item", Data[Iteam], "Date", Data[Date], "Value", Data[Value] ),
                        [Date], ASC
                )
            )
        )
  • Anonymous's avatar
    Anonymous
    Not applicable

    I find Power Query to be better to handle this type, of what I call, heavy lifting.  I attached the PBIX below so you can see all the steps, but basically just grouped the data by your Group Column, and then added an index column and used that to create a simple measure.  

     

    Here's the final table from Power Query:

     

    Then all you need is a simple calculate measure:

     

    Quantity Earliest 2 = CALCULATE( SUM ( Table1[Quantity] ), Table1[Index] <= 2)

    which gives you this:

     

     

    For me (and this is just my opinion) that way is much simpler, but to each there own!

     

    PBIX File:

    https://1drv.ms/f/s!AoQIGRpzoxRH8lEXcUUXYVtr5vO2