Measure to sum another aggregated measure's data - powerbi

I am working on a report that has data by month. I have created a measure that will calculate a cost per unit which divides the sum of dollars by the sum of production volume for the selected month(s):
Wtd Avg = SUM('GLData - Excel'[Amount])/SUM('GLData - Excel'[Production])
This works well and gives me the weighted average that I need per report category regardless of if I have one or multiple months selected. This actual and budget data is displayed below:
If you take time to total the actual costs you get $3.180. Where I am running into trouble is a measure to sum up to that total for a visual (This visual does not total sadly). Basically I need to sum the aggregated values that we see above. If I use the Wtd Avg measure I get the average for the total data set, or .53. I have attempted another measure, but am not coming up with the correct answer:
Total Per Unit Cost = sumX('GLData - Excel','GLData - Excel'[Wtd Avg])/DISTINCTCOUNT('GLData - Excel'[Date])
We see here I return $3.186. It is close, but it is not aggregating the right way to get exactly the $3.180:
My Total Per Unit Cost formula is off. Really I am simply interested in a measure to sum the post aggregated Wtd Avg measure we see in the first graph and total to $3.180 in this example.
Here is my data table:

As you probably know already, this is happening because measures are dynamic - if you are not grouping by a dimension, they will compute based on the overall table. What you want to do is to force a grouping on your categories, and then compute the sum of the measure for each category.
There are 2 ways to do this. One way is to create a new table in Power BI (Modeling tab -> New Table), and then use a SUMMARIZE() calculation similar to this one to define that table:
SUMMARIZE('GLData - Excel',[Category],[Month],[Actual/Budget],"Wtd Avg",[Wtd Avg])
Unfortunately I do not know your exact column names, so you will need to adjust this calculation to your context. Once your new table is created, you can use the values from that table to create your aggregate visual - in order to get the slicers to work, you may need to join this new table to your original table through the "Manage Relationships" option.
The second way to do this is via the same calculation, but without having to create a new table. This may be less of a hassle. Create a measure like this:
SUMX(SUMMARIZE('GLData - Excel',[Category],[Month],[Actual/Budget],"Wtd Avg",[Wtd Avg]),[Wtd Avg])
If this does not solve your issue, go ahead and show me a screenshot of your table and I may be able to help further.

Related

power bi measure with 2 conditions 2 calculate

I am trying to create a measure which will calculate the Total Project Revenue
while I have 2 different projects. For each project there is a different calculation:
for Hourly project the calculation should be: Income * BillHours
for Retainer project the calculation should be: Income*TotalWorkinghours
I wrote the below DAX:
enter code here : Total project revenue = IF(max(DimProjects[ProjectType])="Hours",
max(FactWorkingHours[Income])[BillHours],max(FactWorkingHours[Income])*
[Total Working Hours])
the rows are calculated correctly but the total in the table is wrong
what should I fix in DAX so the total of all raw will correct as well.
The total Revenue should be 126,403.33
Thank you in advance
you can find here the table with the results
It's hard to say exactly what your measure is doing because, as written here, that is not a valid measure. I pasted it into the DAX Formatter, which I would recommend for formatting and pasting here into code blocks, and the measure was invalid. It would also be helpful to post the other measures this measure references, eg. [Bill Hours] and [Income Hours].
That being said, I think I can kind of tell what's going on. Your total is probably wrong because the filter context at the total level is being based of the condition where:
MAX ( DimProjects[ProjectType] ) = "Retainer" (or some other value not in your shared snippet)
That is because when you consider the MAX of a string, the higher alphabetical order is considered. Therefore, "Retainer" > "Hours". So at the total level, your table is outputting—more than likely, I can't be certain without more information—the false condition of your measure:
MAX ( FactWorkingHours[Income] ) * [Total Working Hours])
There is a better way to handle your intended outcome. IF statements, in the way you are attempting to use it, are rarely used in a calculated measure. You may be better off trying a calculated column without using the MAX functions. Again, I can't give an exact code recommendation without more context. Hope that sends you in the right direction!

Getting measure to only show positive values in matrix Power BI

I'm new to DAX. Looking for your expertise. Looked all over the web but couldn't find a proper solution.
I have a matrix that shows several factories and it's inventories, the rows being factory and SKU. I've created a measure that's the difference between two other measures. The overall idea is: I have a inventory quantity and an orders volume. I defined a "balance" measure that's inventory - sales. That is, what is still left for sale.
Normally it works fine, but when I have a negative value in balance, things get messed up. The subtotal in the factory row sums all the numbers, including negatives, giving me a balance subtotal that is smaller than it's supposed to be. I can't count the negatives. So I've tried to solve this by defining the measure as
Balance = IF([Inventory]>[Sales],[Inventory] - [Sales],BLANK())
Now this works fine visually to display only the positive values in balance, but still sums up the negatives in the factory subtotal.
How can I make this measure to only show and sum up the positives?
I appreciate your help.
P.S.: the inventory and sales measures are basically SUM's of different tables for simplicity and understanding by my part
Matrix with measures. The columns are "Estoque" as inventory, "Embarque programado total" as sales and "Saldo Disp. Venda" as the balance
Create a measure with the below code.
Balance = CALCULATE(SUM([Inventory]) - SUM([Sales]), FILTER(Table1, [Inventory]>[Sales]))
As it turns out, I was able to find a solution through trial and error. I changed my measure to (FatoEstoque is the table that contains the inventory numbers):
Balance= CALCULATE([Inventory]-[Sales],FILTER(FatoEstoque,[Inventory]>[Sales]))
Although I'm not even sure why it works (lol), it works! So I'm not complaining. This measure only sums up the positive values, showing the correct subtotal as I needed.
Filtering the Inventory table to values where [Inventory]>[Sales] works, but adding another filter with the Sales table and the same condition don't.
Here is an image comparing the results. The new measure is called SaldVender2

Calculate % of two columns Power BI

I want to calculate % of two columns which are already in %.
I want to calculate formula like
Target achieved= ACTUAL/TARGET
But here is ACTUAL is already a measure/calculated metrics so I'm not able to divide these two columns.
Any help would be appreciated..
Make sure both target and actual are actually numbers and not strings. You can do it in transform data (aka Power Query) part, before data is loaded into the report.
After that you should be able to create the measure you want, e.g. something like that:
UPDATE : What happens if Actual is not a column, but a measure?
If Actual measure is based on the columns in the same table as target you shouldn't have a problem. You cannot combine measure and column in the same formula. Measure is an aggregated field and needs to be grouped by another field (if you are familiar with SQL,think of SUM and GROUP BY). Coming back to your problem, you need to create measure out of "Target" column as well (notice I have in the formula SUM('Table'[Plan]) which makes it a measure). Than you can use both of them in the formula, but of course you need to "group" them by something(e.g. date) otherwise it will just show you a total.

Power BI DAX Cannot display correct monthly of last year's figures in a Matrix visual

I have a "strange" problem in visualizing the values of the "last" year (that is the most current year with data of a full year). In the example delivered it is 2019 which holds the bookings facts. The year should be derived by a related table (LetztesVollesJahrDim) that holds a min/max date and year value for each company/entity. The DateDim table holds all dates and is configured to be the Date dimension. 
The relations are shown in the graphic below.
I created a Report that should display different matrix tables with different values:
one, that shows the last full year's monthly values by Cost Center (which works correct)
one, that shows all years monthly values including an estimated value for the current year (2020) (which also works correct)
one, that could drill down to the details level of the Facts and display the figures per month (in columns) of the last full year (i.e. 2019) putting the Cost Center and other groups down the most detailed level into rows. This Matrix makes use of Calculated Measures created with Tabular Editor.
At this point I can here you say... try it without the Calculated measures and indeed I did that by simply displaying a Card that got a Visual Filter to DateDim[M]=7 to simulate the appliance of each matrix's column. Problem is the same: The Month filter of the Visual (or within the Calculated Measure) is ignored and the yearly sum is displayed (~48k) which is wrong.
As I am currently an Expert in SQL Server DBMS but not in the Architecture of Power BI's DAX Models I am not truely aware about the consequences when and why filters are removed, ignored, overwritten or added at which level of modeling.
Originally I tried to create a simple Calculated Measure that reflects the last full year of the company. That works, but its usage in the huge Matrix was impossible as it was calculating forever. That's why I created the simple table "LetztesVollesJahrDim" to hold a persisted value for each company.
The idea is simple: Create a Query that inner joins these tables and display the Sum for each month [M] like this:
Fact[Turnover] - Fact[CompanyKey] -> CompanyDim[CompanyKey] <-> LastFullYear[CompanyKey] - LastFullYear[MostCurrentYear] -> DateDim[Y] - DateDim[DateKey] -> Fact[StapleDateKey]
So, what is the Problem?
I tried a couple of DAX queries and all come up with a different wrong value.
Following three different approaches for a Calculated Measure "Sum LY":
1. 
Σ LY = CALCULATE(SUM(KontobuchungenFact[UmsatzNegiert]), DATESBETWEEN(DateDim[DateKey], DATE(2019, 1, 1), DATE(2019, 12,31)))
2. 
Σ LY = CALCULATE(SUM(KontobuchungenFact[UmsatzNegiert]), SAMEPERIODLASTYEAR(DateDim[DateKey]))
[
3. 
Σ LY = CALCULATE(SUM(KontobuchungenFact[UmsatzNegiert]), KEEPFILTERS(DateDim[M]), USERELATIONSHIP(DateDim[J], LetztesVollesJahrDim[AktuellstesJahr]), USERELATIONSHIP(DateDim[DateKey], KontobuchungenFact[StapelDateKey]))
 
Filters being applied on the page/visual:
CompanyKey
DateKey >= 2018-01-01 (page filter that limits the displayed rows in yearly matrix to the last 3 ys)
Some other irrelevant keys
Visual configuration:
Relations:
Values/Rows in the LetztesVollesJahrDim table:
Calculated Measures/Table in Tabular Editor showing the calculation of the "01 Jan" column of the first Matrix, which displays correct results:
Impression of the Report:
So in summary I need a clue/DAX formula that recognizes the Monthes in each column and ideally uses the relations to the last year table trespassing the year's filter through DateDim to the Facts.
It is funny, that the upper matrix works, but not the one on the bottom. It is not possible to use the calculated measures approach of the first matrix in the last matrix because the performance would drop to > minutes calculation. So I cannot use the same approach and need a fast one.
Anybody an idea? :-)

Running Total By Date in Visualization

I'm trying to create a line chart visualization that shows a constantly increasing sum over time. I think this would be called a cumulative total or a running total, but most of the questions I've seen on here have been about showing a total at the bottom of a matrix, subtotals, etc. Instead, I just want to visualize the units from the previous date being added to the current date, and so on. Not sure if this would be a custom column in the dataset or if there is an existing function for this.
Any help is appreciated. Thanks!
Goto Quick Measures, in the "Calculation" dropdown, select "Totals - Running Total", pull in Base Value (what you want to aggregate) and Field (probably your calender) and here you are!