Measure with Sum using Calculate and IF not showing totals correctly in power bi - powerbi

I have a requirement in power bi to display the amount value only for the minimum date selected by the user in the slicer. So created below measures..
For capturing the minimum selected range
StartDate = CALCULATE(min(‘DATE’[DATE]),ALLSELECTED(‘DATE’[DATE]))
For Displaying the amount only for the minimum date.
OP = if(SELECTEDVALUE(‘DATE’[DATE]) = [StartDate],
CALCULATE(sum(MEASUREMENTS[OPENING_BASE_VAL]),DATESBETWEEN(‘DATE’[DATE],[StartDate],[StartDate])),0)
I am getting desired output, but the grand-total for this measure becomes 0 as show in below image. Any help much appreciated.

You are getting 0 in the total because
SELECTEDVALUE(‘DATE’[DATE]) in your second formula returns blank, so your IF expression reads as " IF BLANK = [Start Date]", which is always false.
SELECTEDVALUE is a syntax sugar for the following code:
IF HASONEVALUE(DATE’[DATE]) then return Date[Date] else return blank. Since in the total you have many values (all dates), you are getting a blank.
To solve the issue, you need to iterate by dates.
OP =
VAR StartDate = [StartDate]
RETURN
SUMX(
VALUES(Date[Date]),
IF(Date[Date] = StartDate, CALCULATE(SUM(MEASUREMENTS[OPENING_BASE_VAL])), 0))
Here, we first save start date into a variable to avoid calculating it multiple times. Then we create a list of dates using VALUES function, and use SUMX to iterate this list, date by date. If currently iterated date is a start date, then values are summed, otherwise you get zero.
If instead of zeros you can use blanks, you can use a more optimal/faster code:
OP =
VAR StartDate = [StartDate]
RETURN
CALCULATE(SUM(MEASUREMENTS[OPENING_BASE_VAL]), KEEPFILTERS(Date[Date] = StartDate) )
Here, we calculate sums only where dates are equal the start date. Since there is no iteration, and there is no "IF", the code is much faster. The total will be the same, only line items will show blanks instead of zeros.

Related

calculated column stops working when exdternal filter used

I have some Fact Revenue, I am trying to group by Conca, and display the values only if negative…
For doing it I have this calculated column:
=
VAR name1 = Revenue[Conca]
VAR name2=
CALCULATE (
SUM ( Revenue[CostOfQuality] ),
FILTER ( Revenue, Revenue[Conca] = name1 )
)
RETURN
if (name2>0, 0, Revenue[CostOfQuality])
It works:
(highest value is 0 as expected):
Now...
If I drag fiscal year it stops working:
Why is it that I see numbers higher than 0?? (I want it to still work even if I bring other filters...)
a calculated column is computed computed once on the whole dataset after the data are loaded, and is basically a "static column".
Whatever the expected result, you are looking for a measure, which gets computed in the current context
Calculated columns and calculated tables are different from measures, since they are static: You can filter them, but they don't recalculate on filter changes.

Calculate the value closest to selected date range

to simplify my question, I have a table like this. The column Quantity represents the change of stock on given date and column Current stock represents the value I want to find.
and a standard calendar table - 'Calendar'[Dates] with unique dates.
I need an outcome like this:
The logic is that the formula has to find the nearest date lower or equal to the min and max range selection, so in this case dates 1.7.2022 and 19.8.2022.
There are obviously many other IDs and Warehouses involved as well as the 'StockTable'[Date] has duplicate values.
The best I could do is something like this for the upper part of the range, but it does not work. Can you please help me?
Latest date stock =
var selectedmaxdate = MAX('Calendar'[Dates])
return
CALCULATE(
SUM(StockTable[Current stock]),
'Calendar'[Dates] <= selectedmaxdate,
LASTDATE('Calendar'[Dates])
)
I guess, that it's a matrix/table visual and ID is a row value there. Your measure was adjusted a little bit, please look.
Latest date stock =
var selectedmaxdate = MAX('Calendar'[Dates])
return
CALCULATE(
SUM(StockTable[Current stock]),
KEEPFILTERS('Calendar'[Dates] <= selectedmaxdate)
)

Converting Blanks to 0 in Dax Causing date slicer to be ignored - Showing Null Values Outside of Date Range

I am trying to building a dashboard that has a date slicer synced to a line and stacked column chart and a matrix. The matrix has many zero values that appear as blank, but I want them to appear as 0 if they are not blank. Prior to changing my measure to have zeroes appear, the matrix functioned correctly in that it was in sync with the date slicer and the data corresponding to the date slicer. But now with this measure below...the matrix is now showing 0s beyond the date ranged selected in the date slicer (almost like a Null in SQL). How can I modify this Dax measure so that it has zeroes rather than blanks, but doesn't display false data beyond the date range selected?
NbrUnpaid =
IF (
CALCULATE([Count],Query1[Paid_Amount] = 0.00 ) = BLANK(),
0,
CALCULATE([Count],Query1[Paid_Amount] = 0.00 ) )
Thank you!
Firstly, your measure can probably be simplified to
[Count]+0
Secondly, you need to wrap your measure in the logic that prevents zero being returned outside of your date ranges. At the moment, you are telling PBI to return a value for every datapoint but you need to prevent that happening by finding the min date and max date of your fact and only returning values within that range.

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date

Aggregate the last value for child categories with DAX

I need to sum the values of stock on hand at a selected date, these values need to roll up into 2 or more categories.
The following measure gives me the on hand value at the lowest level item, but when it rolls up to the sub Category or Category level, it sums all the values and not the LASTNONBLANK per child item.
On Hand = CALCULATE(SUMX(Stock,[SOH]),FILTER('Calendar',[Date] <= LASTNONBLANK('Calendar'[Date],SUM(Stock[SOH]))))
My data set is similar to this:
Now to get the last SOH value where date <= 10 Dec 2017 works with my measure, with results like this.
As soon as I need to roll the aggregation up by removing the Size column the sum does not work as expected anymore.
This is what I need it to look like:
Similar to that I need the Category level to sum all the LASTNONBLANK values of the lowest level items, like this:
Any help would be appreciated.
I normally prefer to use measures rather than calculated columns in DAX but, because the relevant SOH values rely on a comparison the lowest level, this is a situation where I would add a calculated column.
Latest SOH:=
if(
CALCULATE(
LASTDATE('Stock'[Date]),
ALLEXCEPT('Stock',Stock[Category],Stock[Sub Category],Stock[Size])
)=Stock[Date],
'Stock'[SOH],
BLANK()
)
Starting from the middle and working out:-
ALLEXCEPT(...) is looking at all entries in the table that have the same value for Category, Sub Category and Size
CALCULATE(...) is then finding each of the last dates where there is a match
='Stock'[Date] is then checking to see if this row is the row with the highest date it can find with this Category/Subcategory/Size combination
If the values do match, then bring through the value of SOH, otherwise leave the cell blank.
Here's what it looks like in PowerPivot:
I wasn't quite sure what you wanted your dates to show. I've just added a measure that takes the LASTDATE of the date column:
And
I hope this helps!
Try to group by columns Category and Subcategory using sumx inside
GROUPBY (
Category,
SubCategory,
“SOH”, SUMX(expression)