PowerPivot 3 month rolling average - powerbi

I need some help creating a measure in PowerPivot. I have Googled and tried all the options I could find with success. I have a Fact table with sales leads. Some of the leads gave us a sell some not. I need to measure the value of the leads. I sum the values and divide it with the number of records I have in the table
Average Total of Leads:=calculate(Table1[Sum of Value]/Table1[Count of Lead name])
My problem is to create the measure which give me 3 months rolling average.
I have tried:
Roll3Average:=[Average Value of leads]/CALCULATE(DISTINCTCOUNT(dimdate[MonthName]),
DATESINPERIOD(dimdate[Dates],
LASTDATE(dimdate[Dates]),-3,Month
)
)
I have tried:
Rolling3Average:=IF(COUNTROWS(VALUES(dimdate[MonthName])) = 1,
CALCULATE(
[Average of Value]/ COUNTROWS(VALUES(dimdate[MonthName] ) ) ,
DATESBETWEEN(
dimdate[Dates],
FIRSTDATE(PARALLELPERIOD(dimdate[dates], -2, MONTH)),
LASTDATE(PARALLELPERIOD(dimdate[dates], 0, MONTH))
), ALL(DimDate)
)
)
I have tried:
Total Sales rolling:=
CALCULATE (averagex(Table1,[Average Total of deals]),
FILTER (ALL ( dimdate),dimdate[Month] >= MAX (dimdate[Month]) -2&& dimdate[Month] <= MAX ( DimDate[Month])))
I cannot get it right.
I hope someone can see where I go wrong.
#Marcus
Click here and see my datamodel Thanks
I have still troubles with my data mode.
I have linked a very simplified example. I hope someone can help me.
Thank you

Note in the example I am using, I am using [Sales] instead of leads.
The main structural change you will want to make is to create a month_index in your dimDates table. The advantage of have that field is that it makes calculating the total over 3 months easier, since it removes having to handle cross year like in your 2nd example. The other advantage is having a month_index will handle non standard calendars, e.g. 4-4-5
To start with:
Sales:=SUM(Data[Qty])
The next part would be to calculate the sales(or leads) over the 3 months. The below we are using the month_index field to quickly define the date range in which we want to sum.
3_Month_Sales :=
CALCULATE (
[Sales],
FILTER (
ALL ( dimdate ),
dimdate[Month_index] <= MAX ( dimdate[Month_index] )
&& dimdate[Month_index]
>= MAX ( dimdate[Month_index] ) - 2
)
)
The next part depends on the ask, since the average could be calculated two ways. The main question is it a 3 month average, or is it based on the numerator being the number of months that have a value greater then 0.
The simple way:
3_Month_Average:=DIVIDE( [3_Month_Sales], 3)
The more complex way, in which I learned you can wrap SUMX in a calculate. The idea being the calculate is looking at the period for your 3 months, and then the sumx is iterating down by year then Month. At the end it is checking if sales is greater then 0, if it then 1 is assigned. Then those 1's are summed
Count_of_Periods :=
CALCULATE (
SUMX (
VALUES ( dimdate[Year] ),
SUMX ( VALUES ( dimdate[Month] ), IF ( [Sales] > 0, 1 ) )
),
FILTER (
ALL ( dimdate ),
dimdate[Month_index] <= MAX ( dimdate[Month_index] )
&& dimdate[Month_index]
>= MAX ( dimdate[Month_index] ) - 2
)
)
And then finally
3_Month_Alternative:=DIVIDE([3_Month_Sales], [Count_of_Periods])
Below would be an image using some random sample data, and how the different fields interact. As part of the example the April 2017 data was removed, to show how the count_of_periods calculation was able to handle the fact there was no data in that period

Related

PowerBI using customer %% as X-Axis

I'm looking to create a line graph with accumulated revenue and -gross profit as 0-100% Value Lines on the Y-axis and then have 0-100% of the amount of customers on the X-axis.
I've managed to get the Y-axis and the accumulated lines working using Months on the X-axis. That's not the hard part though, I need to get customer count 0 - 100% on the X-AXIS and I cannot seem to figure it out.
No particular parameters desired i.r.t. the customer accumulation. We just want to be able to see how much the sales are rising along with the relative distinct count of customers in our database.
This way we can see that the first 20% of customers hold i.e. 50% of the revenue etc.
It's a bit weird, I've tried adding custom columns to calculate the percentage of a customer to the grand total of distinct counts but I cannot seem to get it to accumulate. Perhaps i'm looking entirely in the wrong direction and there's a better solution to this. I'd appreciate any help!
KR,
Maarten
You can make the x-axis as a calculated column. If you don't already have a Customer dimension table, then you can create a new calculated table as follows:
CustomerAxis =
VAR CustomerRev =
ADDCOLUMNS (
DISTINCT ( Data[Customer] ),
"CustomerRevenue", CALCULATE ( SUM ( Data[Revenue] ) )
)
VAR TotalRev = SUM ( Data[Revenue] )
VAR TotalCustomers = DISTINCTCOUNT ( Data[Customer] )
VAR CumulativeCols =
ADDCOLUMNS (
CustomerRev,
"CumulativeRevenue",
SUMX (
FILTER ( CustomerRev, [CustomerRevenue] >= EARLIER ( [CustomerRevenue] ) ),
[CustomerRevenue]
),
"CumulativeCount",
COUNTROWS (
FILTER ( CustomerRev, [CustomerRevenue] >= EARLIER ( [CustomerRevenue] ) )
)
)
RETURN
ADDCOLUMNS (
CumulativeCols,
"% of Customers", DIVIDE ( [CumulativeCount], TotalCustomers ),
"% of Revenue", DIVIDE ( [CumulativeRevenue], TotalRev )
)
Then you can drag and drop these last two % columns into a line chart to get the desired curve.
PBIX file I created: https://www.dropbox.com/s/w6trky7t0h42gkp/Pareto.pbix?dl=0

How can I get DAX to return just the record with a date closest to the slicer?

I'm hoping someone can help as I've completely run out of ideas.
I'm working on performance reporting data, producing a number of visuals to summarise the most recent data. To allow users to retrospectively produce reports from previous quarters, I have added a date slicer as a way to "View data as at xxxx date".
Here's a rough representation of my data table - the due dates are in English format (dd/mm/yyyy):
The ratings are calculated in another system (based on a set of targets), so there are no calculated columns here. In reality, there are a lot more measures that report on different time periods (some weekly, some annually, etc) and there are different lags before the data is "due".
I eventually managed to get a measure that returned the latest actual:
MostRecentActual =
VAR SlicerDate = MAX ( Dates[Day] )
RETURN
CALCULATE (
SUM ( Data[Actual] ),
Data[Data due] <= SlicerDate,
LASTDATE ( Data[Data due] )
)
I'm not completely sure I've done it right but it seems to work. I'd be happier if I understood it properly, so explanations or alternatives would be welcomed.
What I'm trying to do now is a basic summary pie chart at the beginning which shows the proportion of the measures that were red, amber, green or unrated as at the date selected. So I would need it to count the number of each rating, but only one for each measure and only for the date that is closest to (but before) the slicer date, which would vary depending on the measure. So using the above three measures, if the slicer was set to 10/10/2019 (English format - dd/mm/yyyy), it would count the RAGs for Q3 2019/20 for measures A an C and for Q2 2019/20 for measure B as there is a time lag which means the data isn't ready until the end of the month. Results:- A: Amber, B: Green, C:Red.
If I were able to create the measure that counted these RAGs, I would then want to add it to a pie chart, with a legend that is "Rating", so it would split the chart up appropriately. I currently can't seem to be able to do that without it counting all dates before the slicer (not just the most recent) or somehow missing ratings from the total for reasons I don't understand.
Any help would be very gratefully received.
Many thanks
Ben
Further update. I've been working on this for a while!
I have created a COUNTAX measure to try to do what I was wanting to do. In some circumstances, it works, but not all and not in the crucial ones. My measure is:
TestCountaxpt2 =
VAR SlicerDate = MAX ( Dates[Date] )
VAR MinDiff =
MINX (
FILTER (
ALL ( Data ),
Data[Ref] IN VALUES ( Data[Ref] ) &&
Data[Data due] <= SlicerDate
),
ABS ( SlicerDate - Data[Data due] )
)
VAR thisdate =
MINX (
FILTER (
ALL ( Data ),
Data[Ref] IN VALUES ( Data[Ref] ) &&
ABS ( SlicerDate - Data[Data due] ) = MinDiff
),
Data[Data due]
)
RETURN
COUNTAX (
FILTER ( Data, Data[Data due] = thisdate && Data[Ref] IN VALUES ( Data[Ref] ) ),
Data[RAG]
)
It produces the following table for a subset of the performance measures, which looks almost ok:
Table showing the result of the TestCountaxpt2 measure:
The third column is the measure above and it seems to be counting one RAG per measure and the dates look correct as the slicer is set to 3rd January 2020. The total for column 3 confuses me. I don't know what that is counting and I don't understand why it doesn't add up to 7.
If I add in the RAG column from the data table, it goes a bit more wrong:
Same table but with RAG Rating added:
The pie chart that is produced is also wrong. It should show 2 Green, 2 Red, 2 Grey (no rating) and 1 Amber. This is what happens.......
Pie chart for the DAX measure, with RAG Rating in the legend:
I can see what it is doing, which is to work out the most recent due date to the slicer in the whole table and using that (which is 1st Jan 2020) whereas I want it to calculate this separately for each measure.
Link to PBIX:
https://drive.google.com/file/d/1RTokOjAUADGHNXvZcnCCSS3Dskgc_4Cc/view?usp=sharing
Reworking the formula to count the ratings:
RAGCount =
VAR SlicerDate =
MAX ( Dates[Day] )
RETURN
COUNTAX (
ADDCOLUMNS (
SUMMARIZE (
FILTER ( Data, Data[Data due] <= SlicerDate ),
Data[Ref],
"LastDateDue", LASTDATE ( Data[Data due] )
),
"CountRAG", CALCULATE (
COUNTA ( Data[RAG] ),
Data[Data due] = EARLIER ( [LastDateDue] )
)
),
[CountRAG]
)
Here's the table it produces:
The reason for Total = 4 for the third column is straightforward. The SelectDate is maximal over all of the Refs in the table and there are only four Refs that match that date.
To fix this and get the totals you're after, you'll need to iterate over each Ref and calculate the SlicerDate for each independently and only then do your lookups or sums.
I haven't tested this code but it should give you an idea of a direction to try:
MostRecentActual =
VAR SlicerDate = MAX ( Dates[Day] )
RETURN
SUMX (
ADDCOLUMNS (
SUMMARIZE (
FILTER ( Data, Data[Data due] <= SlicerDate ),
Data[Ref],
"LastDateDue", LASTDATE ( Data[Data due] )
),
"SumActual", CALCULATE (
SUM ( Data[Actual] ),
Data[Data due] = EARLIER ( [LastDateDue] )
)
),
[SumActual]
)
Going inside to outside,
FILTER the table to ignore any dates beyond the SlicerDate.
Calculate the LastDateDue for each Ref using SUMMARIZE.
Sum the Actual column for each Ref value using its specific LastDateDue.
Iterate over this summary table to add up SumActual across all Refs in the current scope.
Note that for 4, only the Total row in your visual will contain multiple Refs since the innermost Data table inside FILTER is not the entire Data table but only the piece visible in the local filter context.

PowerBI visual with cumulative total over quarters and another field

I have the following graph created. It tracks the count of a certain even in a quarter by groups (i erased the group names and renamed them (ABC's due to sensitive data).
I need the graph to show the cumulative value that is to say for example. Q1 A=1, Q2 A=3, Q3 A=5.
I have played around with quick measures but I can't seem to make them breakdown the accumulation by group, Only quarter (Q1 =1, Q2 =6, etc).
I think i need to create a quick-measure of a quick-measure but I am not sure the order and what the measures would look like.
There are only 2 relevant fields: date_of_event and group
X axis: date of event (by year and quarter), group
y axis: count of date_of event
Thanks
For this, you'll definitely benefit from a date dimension and a dimension for your group. There are many template date dimensions out there, but I'm partial to mine. A group dimension for you may be as simple as just taking the distinct values of your existing [Group] field.
Time intelligence is basically always easier when your model is dimensionalized.
With that, you'd set up relationships as below:
'DimDate'[Date] -1:N-> 'YourEventTable'[Date_Of_Event]
'DimGroup'[Group] -1:N-> 'YourEventTable'[Group]
With that in place, you can use the built-in time intelligence functions or roll your own (examples of rolling your own in my linked date dimension repo).
Events = COUNTROWS ( 'YourEventTable' )
Events YTD = TOTALYTD ( [Events], 'DimDate'[Date] )
If you need an all-time cumulative, instead, you can use this:
Events All-time Cumulative =
VAR CurrentDate = MAX ( 'DimDate'[Date] )
RETURN
CALCULATE (
[Events],
ALL ( 'DimDate' ),
'DimDate'[Date] <= CurrentDate
)
Make sure to always use dimension fields for axis labels and such, and never the same from the fact table.
I had encounter it early this week and below is my DAX for the Cumulative total measure,
Cumulative Total =
CALCULATE (
SUMX (
Table,
IF ( DISTINCTCOUNT ( Table[UserID] ) > 0, 1, 0 ) //Put your Group Here
),
FILTER (
ALLSELECTED ( Table ),
Table[InitialAccessDate] //Date of event
<= MAX ( Table[InitialAccessDate] ) //Date of event
)
)
I hope it helps!! Cheers!!

PowerBI - Cumulative Total with Multiple Criteria

New to PowerBI, so forgive me for the description here. I'm working with a dataset of retail headcount sensors, which gives me a table of locations, timestamps, and a count of shoppers:
Room TimeStamp Count_In
123 3/13/2019 8
456 4/4/2019 9
123 3/28/2019 11
123 3/18/2019 11
456 3/22/2019 3
etc...
I'm trying to calculate a running total for each "room" over time. The overall running total column is easy:
C_In =
CALCULATE (
SUM ( Sheet1[In] ),
ALL ( Sheet1 ),
Sheet1[Time] <= EARLIER ( Sheet1[Time] )
)
But I'm unable to figure out how to add that second filter, making sure that I'm only summing for each distinct location. Help is appreciated!
Your ALL function removes all context on Sheet1, try using ALLEXCEPT to keep the row context of the Room.
C_In =
CALCULATE (
SUM ( Sheet1[In] ),
ALLEXCEPT ( Sheet1, Sheet1[Room] ),
Sheet1[Time] <= EARLIER ( Sheet1[Time] )
)

YTD measure calculated separately for each month

I have a measure calculated in the context of a selected month defined as:
MyMetric = COUNTROWS ( FILTER ( Entities, [Incident Count] > [Target] ) )
I need to calculate the YTD number while calculating each month separately. This is because a single Entity that exceeds the Target in two months needs to be counted twice, whereas a simple YTD calculation would only include it once. For example, when reporting March, a correct result is achieved with:
[MyMetric YTD] = [MyMetric]
+ CALCULATE ([MyMetric] , DATEADD(DateTable[Date], -1 , MONTH))
+ CALCULATE ([MyMetric] , DATEADD(DateTable[Date], -2 , MONTH))
Obviously, this is not the right way to do it. How can this kind of calculation be written efficiently?
Let's suppose that you have a Month column in your DateTable. If not, then you can create one.
Then you can try something along these lines:
MyMetric YTD
= SUMX(
CALCULATETABLE(
VALUES( DateTable[Month] ),
DATESYTD( DateTable[Date] )
),
[MyMetric]
)
Basically, you get a list of each month in the year so far and then sum your measure value for each one of those months.