Forum Discussion
DAX Count consecutive days
- 2 years ago
Add a calendar table and an index column to facilitate the calculation; but it's never for a novice as it leverages embedded table iteration.
(2023/11/23 is marked as non-working day on purpose; therefore 2023/11/24 is calculated as consecutive day)
Hi siumui
Here's an example of how Count could be computed in a calculated column (PBIX attached).
Count =
-- Summarize DATE & ID combinations for current ID
VAR SummaryDateID =
CALCULATETABLE (
SUMMARIZE ( Data, Data[DATE], Data[ID] ),
ALLEXCEPT ( Data, Data[ID] )
) -- Get current Date
VAR CurrentDate = Data[DATE] -- Get earliest Date for current ID
VAR MinDatePerID =
MINX ( SummaryDateID, 'Data'[DATE] ) -- @RunID uniquely identifies the current run
-- It is defined as the difference between
-- 1. The workday count from MinDatePerID and current row's date; and
-- 2. The "rank" of a given date
VAR AddRunID =
ADDCOLUMNS (
SummaryDateID,
"@RunID",
VAR WorkdayIndex =
NETWORKDAYS ( MinDatePerID, Data[DATE] )
VAR DateRank =
RANK (
DENSE,
SummaryDateID,
ORDERBY ( Data[DATE], ASC ),
DEFAULT,
PARTITIONBY ( Data[ID] )
)
RETURN
WorkdayIndex - DateRank
) -- Retrieve the RunID for the current row's Date.
VAR CurrentRunID =
SELECTCOLUMNS ( FILTER ( AddRunID, 'Data'[DATE] = CurrentDate ), [@RunID] ) -- Retrieve the rows for the current run.
VAR CurrentRun =
FILTER ( AddRunID, [@RunID] = CurrentRunID ) -- Compute the rank of the current row's Date within the current run
VAR Result =
RANK ( DENSE, CurrentRun, ORDERBY ( Data[DATE], ASC ) )
RETURN
Result
There could be some simplifications possible but at least this is a working calculation.
Regards
- siumui2 years ago
Helper I
Hi OwenAuger,
Thank you for taking the time to help me! I'm greatly appreciate it! Everyone who post a .pbix in here helping me, I cannot open it due to different version. I have not work with rank before and this is a chance for me to work with rank from you codes. Your codes will teach me more and I get to learn new things! Thank you for everything. Have a wonderful day!!