Find everything you need to get certified on Fabric—skills challenges, live sessions, exam prep, role guidance, and more. Get started
Scenario:
It is always necessary to group consecutive dates before proceeding to the next step of calculation when we are at work, which can be resolved by using the DAX function or Power Query in Power BI Desktop.
The specific operations are:
Sample data:
Table Date1:
Expected Results:
Method 1:Use the DAX function to group
rank = RANKX(ALL(Table1),'Table1'[date],,ASC)
Measure [if]
By subtracting the current date from the next date, it is a continuous date if it is equal to 1, and it is not a continuous date if it is not equal to it, and it is judged by the IF() function.
if =
var _current = MAX(Table1[date])
var _next = CALCULATE (MAX ('Table1'[date]),
FILTER (ALL(Table1), 'Table1'[rank] = MAX ('Table1'[rank]) + 1)
)
var _datediff =
DATEDIFF (_current, _next, DAY )
RETURN
IF ( _datediff = 1, 0,1 )
Measure [accumulative]
Accumulate the value of [IF] by date.
accumulative =
SUMX (
FILTER ( ALL ( Table1 ), 'Table1'[date] <= MAX ( 'Table1'[date] ) ),
[if]
)
Measure [Group_consecutive days]
Compare the current [accumulative] with the previous [accumulative], If not equal, it is the current value, if not, it is the current value + 1.
Group_consecutive days =
VAR _current =
MAXX (
FILTER ( ALL ( Table1 ), 'Table1'[rank] = MAX ( 'Table1'[rank] ) ),
[accumulative]
)
VAR _previous =
MAXX (
FILTER ( ALL ( Table1 ), 'Table1'[rank] = MAX ( 'Table1'[rank] ) - 1 ),
[accumulative]
)
RETURN
IF ( _current <> _previous, _current, _current + 1 )
Result:
Method 2: Use Power Query to group consecutive dates.
Table Date1 -- Index Column -- From 0.
Enter the following code:
#"Added Index" [date] {[Index]+1}
Replace it with null.
Result:
Summarize:
Above we have realized the grouping of different consecutive date periods by means of DAX and Power Query respectively, hope this article can help you to solve a similar problem.
Author: Liu Yang
Reviewer: Kerry Wang & Ula Huang
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.