DAX SUM previous period integer value - powerbi

This issue seemed to be easy at the first glance but I have been trying to solve it for a while.
enter image description here
I would like to dynamically sum the previous period sales in a power pivot measure. The thing is that my period column is a integer value not a date.
I manage to calculate the previous period but I did not manage to set it up as a filter value:
Max(Table1[Period])-1 --> this gives me the previous value of the period field
However when I want to add this as a filter of a calculated measure it doesn't work: --> Calculate(
Sum(table1[Sales]), Filter(table1,Max(table1[Period])=Max(table1[Period])
)
I tried simply this one as well: Calculate(Sum(table1[Sales]), table1[Period] = table1[Period] -1 )
but neither of them are working. I though that I do it with calculated column however I would rather do it with measure.
Can you please help me?
Expected result:

Create measure:
Previous Sales:=
CALCULATE( SUM(Table1[Sales]),
FILTER( ALL(Table1), Table1[Period] = MAX(Table1[Period]) - 1))
It will give you dynamic previous sales. Please note: it relies on the fact that periods increment by 1.
If you need to summarize Previous Sales, create a second measure:
Total Previous Sales:=
SUMX( VALUES(Table1[Period]), [Previous Sales])

Related

Max value of a SMA (Simple Mobile Average) measure in selected range

I have a measure, an SMA (Simple Mobile Average), and I need to calculate the MAX of it.
It should be simple, but I can't find what am I doing wrong.
In my case I have a table (allDataCSV). Each row represents an event, and it has a DATE. I can calculate the num of events that occur in when filtering the table (just count rows):
Count = COUNTROWS()
And my SMA is calculated this way:
CountSMA5Days = AVERAGEX(
DATESINPERIOD(allDataCSV[Day],LASTDATE(allDataCSV[Day]),-5,DAY),
[Count])
I want to calulate the MAX value of [CountSMA5Days]. It is a measure, not a field, so I cant use MAX. I have tried MAXX, with no luck:
MaxSMA = MAXX(allDataCSV,[CountSMA5Days])
It returns me '1', and I suppose it is because it evals row by row, and, in ths case, [CountSMA5Days] returns an average of 5 'ones'
Could you help me, please?
Thanks!
EDIT:
Thans to #Mik, who guided me to solution. The right meassure is:
MaxSMA = MAXX(
all(allDataCSV[Day])
,[CountSMA5Days]
)
That's it!!!
The problem with your measure can come from CALCULATE() that you get by enclosed measure.
I mean your measure MaxSMA = MAXX(allDataCSV,[CountSMA5Days]) DAX converts to MaxSMA = MAXX(allDataCSV,CALCULATE([CountSMA5Days])). So, all data in rows filters your measure. Try the same trick as you did with AVERAGEX()
MAXX(
DATESINPERIOD(allDataCSV[Day],LASTDATE(allDataCSV[Day]),-5,DAY)
,[CountSMA5Days]
)
I believe that DAX will convert it to
MAXX(
DATESINPERIOD(allDataCSV[Day],LASTDATE(allDataCSV[Day]),-5,DAY)
,CALCULATE(
AVERAGEX( -- your measure
DATESINPERIOD(
allDataCSV[Day]
,LASTDATE(allDataCSV[Day]) --= date from current iteration of MAXX
,-5
,DAY
)
,CALCULATE([Count])
)
,allDataCSV[Day]= date from current iteration
)
)
I didn't check the measure. Hope you'll manage to fix the issue.

Power BI Calculate distinct impacting when I use filter

I made a measure that is as follows:
wo = CALCULATE(
DISTINCTCOUNT('Table1'[won]),
ALLEXCEPT(Table1, 'Table1'[flag]),
ALLEXCEPT(Calendar,Calendar[End of Week]),
FILTER(Table1,[flag]="Y")
)
I want the total amount of items in 'won' column with the flag = 'Y'. But when I use one date range filter [End of Week] I had problem because my total amount keeps changing and shouldn't change, I want the total of my entire table regardless of date.
This measure works without 'Y' flag, but it's not what I need:
wo= CALCULATE(
DISTINCTCOUNT('Table1'[wo]),
ALL(Calendar)
)
Could you please help me how to adjust this measure?
Solved using this DAX CODE:
wo= CALCULATE(
DISTINCTCOUNT('Table1'[won]),
FILTER(ALL(Table1),[flag]="Y")
)

Calculating the percentage of grand total by category with DAX for one category only

I need help calculating the percentage of each category in a column (based on the grand total) in DAX but for one specific category.
This is how the data is structured. Each row is an individual transaction with an ID column and item column.
I need to get the % of transactions that are for bagels only. This is my sql code I currently use.
`Select 100 - CAST(count([Items])
- count(case [Items] when 'Bagel' then 1 else null end) AS FLOAT)
/ count([Items]) * 100 as Percent_Bagel
from Items_Table where Items != 'Coffee'
and Items != 'Muffin'`
I need this to be converted to a DAX formula to use in a Power BI measure if possible, but I am new to DAX and don't know where to begin.
Thank you.
The "right" implementation for you always depends on the context. You can achieve your goal through different approaches.
I have used the following:
Measure =
DIVIDE(
-- Numerator: Filter all Bagel's transaction and count them
CALCULATE(
COUNT('Table'[Transaction ID]),
FILTER('Table', 'Table'[Item] = "Bagel")
),
-- Denominator: Remove any filter - essentially fixing the full table - and count all transactions we have
CALCULATE(
COUNT('Table'[Transaction ID]),
ALL('Table'[Item])
),
-- If something goes wrong with the DIVIDE, go for 0
0
)
You may also use the filters to rule out all measures that are not blank.
Without measure filter
With measure filter (Other categories are gone)
Hope this is what you are looking for!

power bi RANKX returning 1 for all rows

I am trying to give rank to each row in daily stock price details table to figure out previous day closing price:
The code I use is:
rank =
RANKX(
FILTER(
ALL(NSE_DAILY_REPORT),
NSE_DAILY_REPORT[SYMBOL]="ADLABS"
),
MAX(NSE_DAILY_REPORT[TDATE]),,
ASC
)
The problem is that it returns a rank of 1 for all rows.
Try changing MAX(NSE_DAILY_REPORT[TDATE]) to NSE_DAILY_REPORT[SCLOSE]
The second argument expects an expression to compare to evaluations of that same expression in the filtered subset. Using MAX will yield that every record gets ranked in a set of just one record, hence the 1 for all rows.
So if I understand correctly your goal is to get the closing price of the day before?
In that case RANKX() is not necessary in contrast to the post you shared as an example. There they create ordinality by creating a ranking first and then perform a pretty inefficient calculation to get the previous in rank. There already is ordinality as you have a date column. Power BI already knows how to interpret that scale, so getting a value for a previous day does not need an additional ranking.
There's tons of posts around stack overflow dealing with this problem. Have a look around to learn more. For your particular problem, the solution will be a calculated column with code looking something like:
PreviousDay =
CALCULATE (
SUM ( NSE_DAILY_REPORT[SCLOSE] ),
FILTER (
ALLEXCEPT ( NSE_DAILY_REPORT, NSE_DAILY_REPORT[SYMBOL] ),
NSE_DAILY_REPORT[TDATE] = EARLIER(NSE_DAILY_REPORT[TDATE]) - 1
)
)
It will do the trick, but it still has some inefficiencies you can improve by looking through other examples like this

Measure in DAX to calculate YTD for chosen month only for Power BI

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
)