Calculate average based on a value column (count) in a pivot table - excel

I'm looking a way to add an extra column in a pivot table that that averages the sum of the count for the months ("Count of records" column) within a time period that is selected (currently 2016 - one month, 2017 - full year, 2018 - 5 month). Every month would have the same number based on the year average, needs to be dynamically changing when selecting different period: full year or for example 4 months. I need the column within the pivot table, so it could be used for a future pivot chart.
I can't simply use average as all my records appear only once and I use Count to aggregate those numbers ("Count of records" column).
My current data looks like this:
The final result should look like this:
I assume that it somehow can be done with the help of "calculated filed" option but I couldn't make it work now.
Greatly appreciate any help!

Using the DataModel (built in to Excel 2013 and later) you can write really cool formulas inside PivotTables called Measures that can do this kind of thing. Take the example below:
As you can see, the Cust Count & Average field gives a count of transactions by month but also gives the average of those monthly readings for the subtotal lines (i.e. the 2017 Total and 2018 Total lines) using the below DAX formula:
=AVERAGEX(SUMMARIZE(Table1,[Customer (Month)],"x",COUNTA(Table1[Customer])),[x])
That just says "Summarize this table by count of the customer field by month, call the resulting summarization field 'x', and then give me the average of that field x".
Because DAX measures are executed within the context of the PivotTable, you get the count that you want for months, and you get the average that you want for the yearly subtotals.
Hard to explain, but demonstrates that DAX can certainly do this for you.
See my answer at the following link for an example of how to add data to the DataModel and how to subsequently write measures:
Using the Excel SMALL function with filtering criteria AND ignoring zeros
I also recommend grabbing yourself a book called Supercharge Excel when you learn to write DAX by Matt Allington, and perhaps even taking his awesome online course, because it covers this kind of thing very well, and will save you significant head-scratching compared to going it alone.

Related

PowerBI DAX: logic to use aggregated table as parameter in functions or another workaround to calculate dataset KPI filtered by any field?

In PowerBI, I need to create a Performance Indicator (KPI) measure which evaluates dataset values in a scale from 0 to 1, with target (1) being the MAX value in a 20 years history. It's a national airport trip records open database. The formula is basically [value]/[max value].
My dataset has a lot of fields and I wish I could filter it by any of these fields, with a line chart showing the 0-1 indicator for each month based on the filters.
This is my workaround test solution:
Table 1 - Original dataset: if I filter something here, below tables also update (there are more fields to the left, including YEAR and MONTH
Table 2 - Reference to original dataset, aggregating YEAR-MONTH by the sum of "take-offs" (decolagens)
Table 3 - Reference to above (sum) table, aggregating MONTH by the max of "take-offs" (decolagens)
Table 4 - 'Sum table' merged to 'Max table' by MONTH as new table: then do [Value]/[Max] and we've got the indicator
So if i filter the original dataset by any fields, all other tables update accordingly and the indicators always stays between 0-1, works like a charm.
TL;DR
The problem is: I need to create a dashboard of this on Power Bi. So I need this calculation to be in a measure or another workaround.
My possible solution: by pure DAX code in the measure field, to produce Tables 2 and 3 so I'll divide the month sum values by their month max value (which will both be produced according to PowerBi dashboard slicers) and get the indicator dinamically produced.
I'm stuck at: I don't understand how can I reference a sum/max aggregate table in dax code. Something like = SUM (dataset[take-offs]) / MAX (SUM (dataset[take-offs])). Of course these functions do not work like that, but I hope I made my point clear: how can I produce this four table effect with a single measure?
Other solutions are welcome.
Link to the original dataset: https://www.anac.gov.br/assuntos/dados-e-estatisticas/dados-estatisticos/arquivos/DadosEstatsticos.csv
It's an open dataset, so I guess there's no problem sharing it. Please help! :)
EDIT: please download the dataset and try to solve this. Personally I think it's a quality statistics doubt that will eventually help others. The calculation works, it only needs a Power Bi Measure port.
Add the ALL formula:
Measure = SUMX(ALL('Table'),[Valor])/SUM('Table'[Max])
Example

Getting workdays for the year in Power Pivot DAX

I need to use the full year's work days in my DAX calculation, but I can't figure out how to get DAX to do that. I have two tables,
1) sales with their respective dates
2) work days table, with end of month and the month's respective work days
I created the relationship between the two, based on the date, and it works, however DAX captures workdays only for the month's where there were sales. How do I get the full year's sum?
As an example, these are the two tables I created:
and connected them as follows:
I then added a calculated field with the following DAX:
=CALCULATE(
SUM(tWorkdays[Days]),
FILTER(
tSales,
YEAR(tSales[Date]) = YEAR(MAX(tSales[Date]))
)
)
and built a pivot table like so:
As you can see, it just captures workdays for the months where there were sales, but I need the entire total, regardless if there were any sales or not.
What can I do to fix this?
I'm not positive about the details, but it has something to do with ALL(), EXCEPT(), and VALUES()
A matter of context, as they say in DAX
https://powerpivotpro.com/2011/06/precedence-part-3-allexcept-vs-all-w-values/
And another explanation:
https://www.sqlbi.com/articles/using-allexcept-versus-all-and-values/

Calculating Weekly Average by user given daily data input in excel pivot table

So I started using Pivot Tables a few weeks ago, but I'm pretty decent at Excel otherwise. I hit an issue that should be an easy fix and I don't see it. I have a document that is tracking Key Performance Indicators for my warehouse packing department. I have 2 tabs in the document that matter (Input Log, and Analysis).
Input log is basically copied from a report generated from my warehouse system. Gives me a USER, DATE, HRS WORKED, ORDERS PACKED, ITEMS PACKED. Using a pivot table I want to see the average hours worked by week for each user.
Currently I can only see the Sum of the hours works and the daily average. How do I also see the weekly average?
[InputLogData][2]
I was able to get the workbook hosted on google drive Packing KPI Workbook
If you create the pivot table, but select to "add to data model",
you will see, in the "Value Fields Settings" selection, a Distinct Count item.
You can then do a Distinct Count of the WE column, and add a column to divide the total hours worked by User, by the total number of Weeks. (See the formula in D4: =B4/C4 )
EDIT: If you want to have the results within the Pivot Table itself, you can add a few calculated columns to your input log.
WE per User is the Unique number of weeks each user works. This formula is an array formula and must be entered by holding down ctrl + shift while hitting enter. Excel will place braces {...} around the formula seen in the formula bar:
=SUM(--(FREQUENCY(IF(User=D2,WE),WE)>0))
Hrs Worked This Wk is the hours worked in the week by the user. This is not really needed, but is in there for when I was troubleshooting the calculations.
=SUMIFS(Hrs_Worked,WE,A2,User,D2)
This will be used to calculate the average for the AvgHrs/Wk column:
=SUMPRODUCT((User='Input Log'!$D2)*Hrs_Worked/WE_Per_User)
This can then be used to create the Pivot Table:
In the Pivot Table, the
Total Hrs is the SUM of Hrs Worked
Hrs-Daily is the Average of Hrs Worked,
Weekly Hrs is the Average of AvgHrs/Wk

How do I get the proper average in a pivot based on pivot data?

I'm trying to get the average number of "on time shipment" based on items rolled up to "ship numbers" and then by "order number". I have one order number in this scenario that is shipped via multiple shipments. It seems to me that after rolling it up via PowerPivot and then creating a pivot table, it's calculating the average based on the total lines of the "order number" instead the pivot.
PowerPivot Data:
Pivot based on data above:
How can I get the average number based on the pivot table rather than the PowerPivot total data of the order number? I'm probably not making any sense, but hopefully the images below explain it better. As you can see, when you roll up the items by ship number then by order number, you'll see that the actual average is 0.6 but the pivot is showing 0.5.
Help!
Technically speaking, the average is correct - if you look at the source data, for some reason all rows are duplicated and if you do regular average calculation, it's actually 0.5.
What you are looking for is calculating average for distinct values, which can be done easily with AVERAGEX function.
I have copied your table and created those 2 Calculated Fields (in Excel 2010, it's Measures):
Average on Time:
=AVERAGE(Table1[On Time])
Average on Time (UNIQUE)
=AVERAGEX(VALUES(Table1[Ship Number]), [Average on Time])
Using AverageX with VALUES() function makes it easier to calculate any expression ONLY for unique values.
If you then put both measures on PivotTable, you should get this:
First column is same as yours (using "regular" AVERAGE function). The second one shows the average calculated over distinct (unique) values of Ship Numbers.
Hope this helps.
PS: This great article by Kasper de Jonge helped me quite a bit with similar scenarios.

Calculating Percent of Total in Power Pivot Model

I have created a power pivot table as shown in the picture. I want to calculate quarter over quarter sales change. For which I have to divide for example corporate family "Acer" 's sales in 2012Q4 by sum of all the corporate family. I am using calculated measure to do this, but I am not sure what formula I can use.
My need is to create two columns, one for 2012Q4 percent of total and one for 2013Q1 percent of total. Then I will create another measure to find the difference. So the formula for 2012Q4 should be like this 1624442 / (1624442+22449+1200+16123) . Any idea which function can help me do it?
It sounds like you are measuring the change in the percent of total for each corporate family from quarter to quarter. You will need to create 3 calculated measures. I'm not sure what your model looks like so I can't give you the exact formula, but here is the idea.
CurrentQtr%ofTotal:= Divide(Sum('Sales'[Units]),Calculate(Sum('Sales'[Units]), All['Product'[Corporate Family])))
PrevQtr%ofTotal:= DIVIDE(CALCULATE(Sum('Sales'[Units]), DATEADD(DimDate[DateKey], -1, QUARTER)),
CALCULATE(Sum('Sales'[Units]), DATEADD(DimDate[DateKey], -1, QUARTER), All('Product'[Corporate Family]))))
Change%ofTotal:= DIVIDE(([CurrentQtr%ofTotal]-[PrevQtr%ofTotal]),[PrevQtr%ofTotal])
I used the divide function because it handles divide by zero errors. You use the ALL function to remove the filter on the Corporate Family column from the filter context. The Change%ofTotal is just to find the differenc. I'm calculating % change but you may just want to subtract.
Here's the link to a good blog post on time intelligence. And here's one on calculating percent of total.
For percentages please follow the tutorial on the Tech on the Net.
Adding another column where you calculate a difference between two pivot columns will not work - this column is "unpivotable", as it relies on a column defintion. You would need to copy and paste pivot as values to another worksheet and do the extra calculation there.

Resources