I've used the new Quick Measures feature of Power BI to build a 3 month rolling average calculation and it's working well. The equation is displayed below. However, when I try to use this metric in a time series visualization, the calculations are displaying three months past the current month, but I'd like for the calculation to stop at the current month.
I've played around with the __DATE_PERIOD variable to no avail. My date filter for the page is set to show all dates in the current months or 12 months prior via a calculated column on the date table.
Is anyone aware of how I can get the visualization to end at the current month?
Average Days to Close Rolling Average =
IF(
ISFILTERED('Date'[Date]),
ERROR("Time intelligence quick measures can only be grouped or filtered by the Power BI-provided date hierarchy."),
VAR __LAST_DATE =
ENDOFMONTH('Date'[Date].[Date])
VAR __DATE_PERIOD =
DATESBETWEEN(
'Date'[Date].[Date],
STARTOFMONTH(DATEADD(__LAST_DATE, -3, MONTH)),
__LAST_DATE
)
RETURN
AVERAGEX(
CALCULATETABLE(
SUMMARIZE(
VALUES('Date'),
'Date'[Date].[Year],
'Date'[Date].[QuarterNo],
'Date'[Date].[Quarter],
'Date'[Date].[MonthNo],
'Date'[Date].[Month]
),
__DATE_PERIOD
),
CALCULATE(
'Closed Opportunities'[Average Days to Close],
ALL('Date'[Date].[Day])
)
)
)
In order to limit what is displayed within your chart, you need to filter the applicable date field so it only displays the dates you desire. In this case, you only want it to include dates <= today.
In order to automatically filter it when it is refreshed, I typically add a custom DAX column to the date table that I can filer on. In this case it would be something along the lines of:
excludeFutureDatesInd = 'Date'[Date] <= TODAY()
You can then add a visual, page, or report filter selecting all dates where [excludeFutureDatesInd] = True.
Not sure if you're still having issues with this, but I'd like to share a hack fix for those landing here. I fixed this issue by filtering on the base data (in your example, this would be "Average Days to Close"). Set a visual-level filter to include only those items where Average Days to Close > 0, and you should get the extra dates cut off the end of the graph.
So long as all of your base data passes through the filter, you should be good.
Related
Below is the sample dataset
The data has two slicers ( date and category ) shown below
I am writing a DAX Statement to multiply the sum(values) * 10 only if the date range is in the current year 2023.
The StartYear gives the start of the current year, firstD gives the lowest date from the date slicer.
Formula =
var new = sum(Test[Value]) * 10
var startyear = DATE(YEAR(TODAY()),1,1)
var firstD = CALCULATE( MIN( Test[Date]), ALLSELECTED(Test[Date]) )
return if( ISFILTERED(Test[Categories]) && firstD >= startyear, new, 0 )
Now when I filter dates to 2023, the total value should be 2300 but it shows as 0
However the DAX works when I select A or B
If we remove the ISFILTERED function then, it gives wrong value, the expected value is 0 because the start date is in 2022, but it shows 650
let me know if that is the right syntax
It looks like you are not using a separate calendar table to handle this, which you need!
In your very last example you have set your slicer to some time late 2022, but the minimum value of 'Test'[Date] for your selected category is in year 2023. Hint: set the slicer to e.g. 2022-12-14, this will include a 2022-date for Category A in your data.
Your measure behaves exactly how it is supposed to, in other words!
To fix this, you need to do the following:
Create a calendar table in your model, this should contain contiguous dates, which is necessary for the filtering method you want
Establish a relationship between the calendar table and existing Test table.
Use the date column from your new calendar table in your slicer and as date reference in your measure
Exactly how to create a calendar table is thoroughly documented on Google, I recommend you search and find an article or video you understand for implementing this.
Lastly: Your use of ISFILTERED in this measure seems strange, since you mention nowhere the requirement of only showing a number if the column you are testing filtering on is filtered, if that makes sense.. :-) The way you describe your calculation, you only need to check whether the selected date range starts in current year.
I am using power BI and I would like to create a line chart which contains values from two tables (sales history and sales prediction). So for the past 12 months, the line should reprensent the sales history and for the next 6 months, the line reprensents sales prediction. Here is what the data looks like, lets say we are in June 2021:
I know there is a way to do it in DAX but I don't know how to do it by myself. Thanks a lot in advance for your help !
You can achieve this by
Delete any relationship between Calendar and the other two tables if there is any, as we are going to use DATESBETWEEN function to calculate
Create two metric like below, you might need to adjust the column names as per your project
Sales History Amount = IF('CALENDAR'[Date] <= TODAY(), CALCULATE(SUM('Sales History'[Amount]), DATESBETWEEN('Sales History'[Date], MIN('CALENDAR'[Date] ), MAX('CALENDAR'[Date]))), BLANK())
Sales Prediction Amount = IF('CALENDAR'[Date] >= TODAY(), CALCULATE(SUM('Sales Prediction'[Amount]), DATESBETWEEN('Sales Prediction'[Date], MIN('CALENDAR'[Date] ), MAX('CALENDAR'[Date]))), BLANK())
Add these two metrics in the table and use the Date from the Calendar table as X axis.
Format the first metric to solid line, and dash line for the second
Calendar should be linked to your tables.
Prediction Amount =
VAR lastSalesDate = MAX('Sales History'[Date])
VAR currentPredictionAmnt =
CALCULATE(
SUM('Sales Prediction'[Amount])
,KEEPFILTERS('CALENDAR'[Date]>lastSalesDate)
)
RETURN currentPredictionAmnt + SUM()
Sales Amount =
SUM('Sales History'[Amount])
I need to calculate headcount while keeping the measure sliceable by any dimension connected to the fact table. Given the nature of my tables and model, what I need to do is a point in time calculation on a Slowly Changing Dimension Type 2.
I managed to make it work using the function KEEPFITLERS, but I need a more scalable function that wouldn't require me to list all the dimensions I want to slice by.
Here is my PowerBI file with sample data: https://gofile.io/d/smS2Hr
Here is a simplified sketch (image) of my model: https://ibb.co/fQYpsdx
Background:
The first measure I am calculating is the number of Employees at the Start of the Period (Employees SoP). If the end-user selects in PowerBI the whole month of January 2020, the Start of the Period is Jan 1st, 2020. Hence, "Employees SoP" for the month of Jan 2020 will give the number of employees on Jan 1st, 2020.
The formula below calculates the correct values for Employees SoP:
Employees SoP =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER(ALL('Fact'), 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
))
RETURN
Result
The problem with the formula above is that, because of the ALL function, the measure is not sliceable by any dimension, i.e., Pay Class and Employment Status (the same number repeats itself).
Results:
Hence, I created this other measure using KEEPFILTERS, and it works perfectly.
Employees SoP KEEPFITLERS =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER(ALL('Fact'), 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
), KEEPFILTERS(PayClass), KEEPFILTERS(EmploymentStatus))
RETURN
Result
The problem with this formula is that I have to list all the dimensions I want to slice by ( e.g., PayClass, EmploymentStatus) inside the DAX formula. This is not very scalable.
I did some experimenting with REMOVEFILTERS but it looks like it does not work with DirectQuery for now, so it wouldn't solve my production problem. Link:
https://learn.microsoft.com/en-us/dax/removefilters-function-dax
QUESTION:
How can I write this measure using an alternative to KEEPFILTERS with which I wouldn't have to list each dimension I want to slice by?
Thank you!
I just managed to solve my problem. I made both relationships to the Dates table "inactive". With that, I could remove the "ALL" function in the DAX formula and now it not only calculates the correct values, but it also slices nicely. I will have to use the USERELATIONSHIP function to calculate more complex measures but, in most of the cases, this simple solution works like a charm.
Employees SoP without ALL =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER('Fact', 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
))
RETURN
Result
I have a calculation that is being done on a weekly basis (x+y/x*40) . 40 is the number of hrs worked per week and x is the num of weeks selected.
I have a relative date slicer using which the user will select the number of weeks. The catch is that there are two kinds of relative weeks - one from the present day and one is the entire week.
If the user selects 2 weeks it will be (x+y/2*40).
I have a calculation called
Tot Weeks = DATEDIFF(MIN( DimDate[Calendar Date] ), MAX( DimDate[Calendar Date]), week )
However, this doesn't work well if I select 'Weeks(Calendar Date)' in the drop down. For the value to be right, I created
Num weeks = DISTINCTCOUNT(DimDate[CalendarWeekOfYear])
Num weeks works fine only when 'Weeks(Calendar Date)' is selected. I am trying to retrieve the parameter passed to the slicer to get my values right.(whether the user selects 'Weeks(Calendar Date)' or 'Weeks' in the slicer).Is there a way to retrieve this or
Is there a way to combine these two?
If you have a slicer like with Weeks (Calendar Date) and Weeks as the two options in the column Slicer[WeekType], then you can pass your selection into a measure like this:
Weeks =
VAR WeekType = SELECTEDVALUE(Slicer[WeekType], <default>)
RETURN IF(WeekType = "Weeks", [Tot Weeks], [Num weeks])
How to construct DAX measure to calculate sum of YTD value for specific month?
Here we have FactTable grouped by months. FactTable is filled with both Actual data and Forecast data. The only way to know when Actual end is information in table [Cut of date] in column [End of YTD]. In table [Cut of date] in column [End of YTD] – it is a single value table – we have the interesting chosen month, for which we want to see the calculation of YTD. In our case it is March. FactTable is updated irregularly every month with usually one month delay. There is no way of linking it to time functions like TODAY because of irregular update.
We would like to have a correct value of YTD displayed in yellow Card Visual for the month [End of YTD]. When we click on the slicer on "2018-03" we get almost what we want – correct value of 66 in the yellow Card. However this solution is not automatic. I want to see correct value automatically when the [End of YTD] month changes, in our case to April or then to May. I do not want it done by user.
My desperate effort can be downloaded from file: DAX YTD.pbix
I pursued the deer in various ways:
By using FILTER function in DAX measures. But it seems that the
FILTER function is to harsh. It is applied to fact table first,
selecting only one month, and then calculating YTD value wrongly. So if
there would be any option for forcing order of calculation and filtering, there would
be hope.
I tried SWITCH function to display proper result
for specific month and 0 or null for other months. Although I
succeed in this, I was not able to take advantage of it. When it
came to filtering I was as hopeless as before. BTW I would be able
to make it if SWITCH produced totals at the end of the table, but it
does not. Surprisingly.
I put some hopes in RELATED function to display proper results in the [Cut off date] table. I have not walk out of the fog so far.
I would appreciate your help.
Update before bounty.
Going to higher level. I have introduced a Category column to FactTable. Please download DAX YTD by category.pbix. So filtering gets more complex now. I would like to have correct YTD figures for Apples category.
Did you use the Date column from the Calendar table, instead of the one from FactTable?
If you use the date column from FactTable, when you apply a filter on the date, it will filter on the fact records which is in March, and then do the calculation afterwards, hence the result 33.
If you use the one from Calendar, when you apply a filter on it, it filters the records on Calendar (which you want to show in the chart), so the underlying calculation will still remain intact.
A working example:
Calendar = CALENDAR(DATE(2010, 1, 1), DATE(2020, 12, 31))
I suggest you to change the calculations of the measures to avoid missing values in some cases:
Total = SUM(FactTable[Value])
MTD = TOTALMTD([Total], 'Calendar'[Date])
YTD = TOTALYTD([Total], 'Calendar'[Date])
UPDATE:
It's much clearer to me what you want to achieve now but it still seems an XY problem to me.
I understand that you want to show the dashboard as is so that users do not need to click/input every time to see what they are supposed to see. That's why I don't get why you need to create a new table to store the Cut off date (End of YTD). How is it going to be maintained automatically?
The relative date filtering solution above actually still works in the .pbix file you've shared. If you drag the Date column from the Calendar table to visual level filters for the yellow card and add the relative date filtering, it should work as below:
For the End of YTD visual, you can use the following measure to get the first day of last calendar month, so you don't need to create another table for it:
End of YTD = EOMONTH(TODAY(), -2) + 1
And hopefully this is what you want to achieve:
Updated file for your reference.
UPDATE again:
I think you'll have to write your own YTD calculation instead of using the built-in one, so that you can make use of the cut off date you defined in another table. Here I assume that you have one and only one row in 'Cut off date'[End of YTD]. Note that I've added ALL() to the filter, so that the yellow card remains the same (66) instead of showing blank when some other rows/filters are clicked:
YTD_Special =
CALCULATE(
[Total],
FILTER(
ALL(FactTable),
FactTable[Date] >= DATE(YEAR(VALUES('Cut off date'[End of YTD])), 1, 1) &&
FactTable[Date] <= VALUES('Cut off date'[End of YTD])
)
)
I would resolve this by adding a calculated column to your Calendar table to categorise each row into either "YTD" or "Other", e.g.
Is YTD =
IF (
[Date] >= DATE ( YEAR ( DISTINCT ( 'Cut off date'[End of YTD] ) ), 1, 1 )
&& [Date] <= DISTINCT ( 'Cut off date'[End of YTD] ),
"YTD",
"Other"
)
I would then add the new Is YTD field to the Visual level filters of your Card visual, and choose YTD from the Basic filtering list. The measure shown can be your simple Total measure: SUM(FactTable[Value]).
This is a far more flexible and resuable solution than any specific measure gymnastics. You will not need an explosion of measures to apply the required logic on top of every base measure - they will all just work naturally. You can apply the filter at any level: Visual, Page, Report, or put it in a Slicer for control by the end user.
I prefer to return text results e.g. "YTD" / "Other" (rather than 1/0, True/False or Yes/No), as this allows for easy extension to other requirements e.g. "Prior YTD" (1 Jan 2017 to 1 Mar 2017). It also is clearer when used in visuals.
Actually I shouldn't claim the credit for this design - this roughly follows how Cognos Transformer's Relative Time functionality worked back in the 90s.
I did something like this in my Periodic/YTD report (last sheet): http://ciprianbusila.ro/
I have used the index value of the month selected (range 1-12) and based on this I have created a measure using max function please see the code below:
ACT = var
ACT_periodic=calculate([Value],Scenarios[Scenario]=values(Scenarios[Scenario]))
var max_month=max(Periods[Period Order])
var ACT_YTD=CALCULATE([Value],Scenarios[Scenario]=VALUES(Scenarios[Scenario]),all(Periods[Month]),Periods[Period Order]<=max_month)
var myselection=if(HASONEVALUE(MRD_view[.]),values(MRD_view[.]),"PERIODIC")
return
switch(
true(),
myselection="PERIODIC",ACT_periodic,
myselection="YEAR TO DATE",ACT_YTD,
ACT_periodic
)