Min value with GROUP BY in Power BI Desktop

纵饮孤独 提交于 2019-12-06 15:02:57

问题


id  datetime             new_column           datetime_rankx
1   12.01.2015 18:10:10  12.01.2015 18:10:10  1
2   03.12.2014 14:44:57  03.12.2014 14:44:57  1
2   21.11.2015 11:11:11  03.12.2014 14:44:57  2
3   01.01.2011 12:12:12  01.01.2011 12:12:12  1
3   02.02.2012 13:13:13  01.01.2011 12:12:12  2
3   03.03.2013 14:14:14  01.01.2011 12:12:12  3

I want to make new column, which will have minimum datetime value for each row in group by id.

How could I do it in Power BI desktop using DAX query?


回答1:


Use this expression:

NewColumn =
  CALCULATE(
    MIN(
      Table[datetime]),
      FILTER(Table,Table[id]=EARLIER(Table[id])
   )
  )

In Power BI using a table with your data it will produce this:


UPDATE: Explanation and EARLIER function usage.

Basically, EARLIER function will give you access to values of different row context.

When you use CALCULATE function it creates a row context of the whole table, theoretically it iterates over every table row. The same happens when you use FILTER function it will iterate on the whole table and evaluate every row against the filter condition.

So far we have two row contexts, the row context created by CALCULATE and the row context created by FILTER. Note FILTER use the EARLIER to get access to the CALCULATE's row context. Having said that, in our case for every row in the outer (CALCULATE's row context) the FILTER returns a set of rows that correspond to the current id in the outer context.

If you have a programming background it could give you some sense. It is similar to a nested loop.

Hope this Python code points the main idea behind this:

outer_context = ['row1','row2','row3','row4']
inner_context = ['row1','row2','row3','row4'] 

for outer_row in outer_context:
    for inner_row in inner_context:
        if inner_row == outer_row: #this line is what the FILTER and EARLIER do

            #Calculate the min datetime using the filtered rows
            ...
            ...

UPDATE 2: Adding a ranking column.

To get the desired rank you can use this expression:

RankColumn = 
  RANKX(
    CALCULATETABLE(Table,ALLEXCEPT(Table,Table[id]))
    ,Table[datetime]
    ,Hoja1[datetime]
    ,1
 )  

This is the table with the rank column:

Let me know if this helps.



来源:https://stackoverflow.com/questions/38570755/min-value-with-group-by-in-power-bi-desktop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!