Difference between multiple dates in the same column based on category

ⅰ亾dé卋堺 提交于 2019-12-24 01:18:46

问题


I have the following problem ..

I have this table:

I want to create a calculated column that tells me the difference of days between two dates of the same code (COD), the difference should be calculated based on the date before the line.

For example:

Using COD B

COD | DATE | days_diff

B |05/01/2018 |

B |09/01/2018 | 4

B |12/01/2018 | 3

In the example image the codes / dates are sorted in sequence, but in reality they are out of order.

I tried to use the following sentence in DAX:

 DATEDIFF(Testing[DATE]; FIRSTDATE(FILTER( ALL(Testing[DATE]) ;Testing[DATE] > EARLIER(Testing[DATE])));DAY)

Explaining what I've tried:

Make the difference between the date on the line and using the EARLIER function to get the most recent date out of the current one.

However, I obtained the following result:

I can not filter COD, so that the analysis of 'EARLIER' is performed only in the same 'group', so I understand the PowerBI is considering all the dates.

Any idea?


回答1:


You're pretty close in idea, but it needs some tweaking. Try this:

Days_diff =
VAR StartDate =
    CALCULATE (
        LASTDATE ( Testing[DATE] ),
        FILTER (
            ALLEXCEPT ( Testing, Testing[COD] ),
            Testing[DATE] < EARLIER ( Testing[DATE] )
        )
    )
RETURN
    DATEDIFF ( StartDate, Testing[DATE], DAY )

The variable StartDate calculates the last date before the current row date. I use CALCULATE to remove all row context except for COD since that is what we are grouping on.

Note: The EARLIER function is not a date/time function, but rather a reference to an earlier row context (before stepping inside the FILTER function). It allows us to jump back a level when we are nesting functions.

Then you just take the DATEDIFF.



来源:https://stackoverflow.com/questions/54044455/difference-between-multiple-dates-in-the-same-column-based-on-category

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