- Optional: Create a calculated field with a name like "Profit no gaps" with a calculation similar to the following:
ZN(LOOKUP(SUM([Profit]),0))
Note: If the data set is missing days, then this step will allow us to treat missing days as having zero profit. If you skip this step use SUM([Profit]) rather than [Profit no gaps] in all following steps.
- Create a calculated field with a name like "Start Date" with a calculation similar to the following:
IF [Profit no gaps] >= 0
THEN NULL
ELSEIF LOOKUP([Profit no gaps],-1) >= 0
THEN MIN([Order Date])
ELSE PREVIOUS_VALUE(#1/1/18#)
END
- Create a calculated field with a name like "Next Profit Value" with a calculation similar to the following:
LOOKUP([Profit no gaps],1)
- Create a calculated field with a name like "End Date" with a calculation similar to the following:
IF [Profit no gaps] >= 0
THEN NULL
ELSEIF [Next Profit Value] >= 0
THEN MIN([Order Date])
ELSE PREVIOUS_VALUE(#1/1/18#)
END
- Create a calculated field with a name like "Days in Streak" with a calculation similar to the following:
DATEDIFF('day', [Start Date], [End Date]) + 1
- Create a calculated field with a name like "# of Streaks" with a calculation similar to the following:
IF [Days in Streak] = 1 THEN
WINDOW_SUM(
IF [Days in Streak] = 1
THEN COUNTD([Order Date])
END
)
ELSEIF [Days in Streak] = 2 THEN
WINDOW_SUM(
IF [Days in Streak] = 2
THEN COUNTD([Order Date])
END
)
ELSEIF [Days in Streak] = 3 THEN
WINDOW_SUM(
IF [Days in Streak] = 3
THEN COUNTD([Order Date])
END
)
ELSEIF ...
END / [Days in Streak]
Note: The calculated fields [# of Streaks] and [Keep only one date per streak group] must include a condition for every possible number of days in a streak. For more explanation on why see the article Using an Aggregate Field to Define the Level of Detail in a Table Calculation
- Create a calculated field with a name like "Keep only one date per streak group" with a calculation similar to the following:
MIN([Order Date]) = WINDOW_MIN(IF[Days in Streak] = 1 THEN [Start Date] END)
OR MIN([Order Date]) = WINDOW_MIN(IF[Days in Streak] = 2 THEN [Start Date] END)
OR MIN([Order Date]) = WINDOW_MIN(IF[Days in Streak] = 3 THEN [Start Date] END)
OR ...
Creating the prep flow is more upfront work, but building the views from the prep output is much simpler compared to building the views with table calculations. The "Grouping Consequtive days.tflx" prep flow demonstrates the following steps and can be downloaded from the right-hand pane.