使用DAX计算每个ID的最新日期

时间:2019-06-24 19:14:07

标签: powerbi dax powerbi-desktop

我在Power BI中有一个像这样的数据集:

ID      FirstDate    LastDate
214443  07/06/2016  07/06/2017
214443  09/11/2016  09/11/2017
214443  28/09/2018  11/06/2019
214443  31/05/2019  11/06/2019

我想创建两个计算列,其中包含每个索引的最新日期。目前,我只能获取所有数据集的最新日期或每行相同的日期。

输出应为:

ID      FirstDate   LastDate    FirstDate2  LastDate2
214443  07/06/2016  07/06/2017      
214443  09/11/2016  09/11/2017  07/06/2016  07/06/2017
214443  28/09/2018  11/06/2019  09/11/2016  09/11/2017
214443  31/05/2019  11/06/2019  28/09/2018  11/06/2019

谢谢!

2 个答案:

答案 0 :(得分:1)

我从这样的数据开始

enter image description here

然后使用查询编辑器添加索引列

enter image description here

然后创建一列以检查单个ID出现的次数:-

Number of ID's Present = COUNTROWS(FILTER('MyTable', 
     (EARLIER('MyTable'[ID]) = 'MyTable'[ID])))

然后想知道每个ID的起始索引以使其变得容易:-

Starting Index = CALCULATE(MIN(MyTable[Index]),FILTER('MyTable', 
     (EARLIER('MyTable'[ID]) = 'MyTable'[ID])))

然后,您可以通过一些简单的方法来完成所需的工作,

First Date 2 = 
    Var NumberofIDsPresent = MyTable[Number of ID's Present]
    Var StartingIndex = MyTable[Starting Index]
    Var CurrentIndex = MyTable[Index]

    Var Only_OneTime_ID_Present = IF(OR(NumberofIDsPresent = 1,CurrentIndex = StartingIndex),1,0)
    Var Multiple_Times_ID_Present = CALCULATE(MIN(MyTable[First Date]),FILTER(MyTable, MyTable[Index] = CurrentIndex - 1))
    var result = IF(Only_OneTime_ID_Present = 1, BLANK(),Multiple_Times_ID_Present)
    return result


Last Date 2 = 
    Var NumberofIDsPresent = MyTable[Number of ID's Present]
    Var StartingIndex = MyTable[Starting Index]
    Var CurrentIndex = MyTable[Index]

    Var Only_OneTime_ID_Present = IF(OR(NumberofIDsPresent = 1,CurrentIndex = StartingIndex),1,0)
    Var Multiple_Times_ID_Present = CALCULATE(MIN(MyTable[Last Date]),FILTER(MyTable, MyTable[Index] = CurrentIndex - 1))
    var result = IF(Only_OneTime_ID_Present = 1, BLANK(),Multiple_Times_ID_Present)
    return result

现在,这使我的数据看起来像这样,

enter image description here

如果有帮助,请接受答案,如果不能解决您的问题,请告诉我。

答案 1 :(得分:0)

仅考虑与FirstDate匹配且日期在当前行日期之前的行,才能在ID列上获取最大值。

Previous Date =
CALCULATE (
    MAX ( Table1[FirstDate] ),
    FILTER (
        ALLEXCEPT ( Table1, Table1[ID] ),
        Table1[FirstDate] < EARLIER ( Table1[FirstDate] )
    )
)