Calculate average within category - powerbi

How to calculate the average of a measure within a category?
For example, in my data model, I have a table "Geo" that contains the field "País" (Country).
In table "Clientes" I have the field "Cliente" (Customer).
This is how the relationship looks like:
The facts table is "Vendas".
I need the average of measure "Margem Líquida *" per country, so I'm using the following measure:
Margem Média País = AVERAGEX(Clientes;[Margem Líquida *])
This is ok on a Country level, but as you can see in the following table I can't compare the value of the measure with the average per country on a Customer ("Cliente") level.
I'd like to have the value of the country level repeated for each customer within the country.
How can I do that? I've tried all sorts of CALCULATE with EARLIER but no luck...
Thanks in advance!

See if either of these work for you:
Margem Média País = AVERAGEX(ALL(Clientes[Cliente]); [Margem Líquida *])
Margem Média País = CALCULATE(
AVERAGEX(Clientes; [Margem Líquida *]);
ALL(Clientes[Cliente]))
If not, then please post a minimal complete verifiable example of your data.
Edit: Something like this might help with the issue you mentioned in your comment.
Margem Média País = CALCULATE(
AVERAGEX(Clientes; [Margem Líquida *]);
ALL(Clientes),
Geo[País] IN VALUES(Geo[País]))

Related

Power BI - Use Column name to create Row and attach Value from that Row to it

I have a table from a survey that reports the score given to a specific employee, and various columns are there to hold each score for each question. Like this table below:
Now, what I want to do is make a row for each question, and in the original table, each question is a column. And I'd like for example, John, to have 1 entry for each question, and the average of that score stored next to each question like in this table here:
.
This shows clearly what I'm aiming for.
I believe I need some sort of pivot or unpivot table going on, but I'm not too sure on the Power BI DAX syntax for creating a new table.
I currently have a table that provides each Employee once, and columns showing their average score for each question, but that is a bit harder to dice up the way I want to. Code pasted below:
ReportTable =
SUMMARIZE(
ALL ( '360Sample'[Name], '360Sample'[Relationship to person being reviewed]),
'360Sample'[Name],
'360Sample'[Relationship to person being reviewed],
"Employee Satisfaction", DIVIDE(CALCULATE(AVERAGE('360Sample'[Treats others with respect/Truly values employees]))+AVERAGE('360Sample'[Encourages and supports staff in developing their skills])+AVERAGE('360Sample'[Provides effective mentoring]),3),
"Quality Product", DIVIDE(CALCULATE(AVERAGE('360Sample'[Consistently strives to provide products above industry quality standards]))+AVERAGE('360Sample'[Takes ownership of project outcome])+AVERAGE('360Sample'[Ensures quality control always happens on products]),3),
"Client Satisfaction", DIVIDE(CALCULATE(AVERAGE('360Sample'[Fosters open, honest, and consistent communication with clients]))+AVERAGE('360Sample'[Responds quickly to client questions and concerns.])+AVERAGE('360Sample'[Successfully communicates contractual needs and requirements with the Client, including schedules and scope and fee increases]),3),
)
Only difference here is that I have an extra attribute of "Relationship" which I'll also need to include but is less important for now. It makes a row of each employee for every unique Relationship, which is 2.
Hello You need to first use the "unpivot" in Power Query to convert your table into this shape: It is not so hard.
Like this:
Then use this DAX Code:
ReportTable =
ADDCOLUMNS (
SUMMARIZE ( 360Sample, 360Sample[Name], 360Sample[ScoreNum] ),
"ScoreAvg", CALCULATE ( AVERAGE ( 360Sample[Score] ) )
)
And It produces:

Tableau: percentage of total for specific dimension / COUNTD IF statement

I have an employee dataset and I'm trying to display the proportion of BAME staff only as a KPI. My dataset has duplicate lines (staff who have more than 1 role) and so I have to use a distinct count of their staff IDs (i.e. cannot use measure values or SUM) as I want to measure ethnicity per person not per role. The only way I can get the % of BAME across the population is by having all other categories visible however I am looking for a way to display the % of BAME across total only. For example in a table calc BAME = 12%, Non-BAME=85% and Unknown=3% - I want to keep the 12% only to put on my dashboard.
I've not needed to do this in Tableau before and I'm quite new to the software. Is there a way to do this? I thought that perhaps I would need to do an IF statement similar to Excel but the below syntax returns an error.
IF [Ethnic Group]="BAME" THEN COUNTD([Staff ID]) / COUNTD([Staff ID]) END
Thank you so much in advance!
COUNTD(IF [Ethnic Group]="BAME" THEN [Staff ID] END)/COUNTD([Staff ID])

Create a measure which divide two KPIs based on different periods

I have a table as presented below.
I would like to calculate KPI (#Handled/#Total Offered) and present it using CREATION YEAR MONTH NUMBER on chart but when I am trying to calculate it, it changes to 100% as #handled = #total offered.
#Total Offered = DISTINCTCOUNT(TABLE[REFERENCE_NUMBER])
#Handled = CALCULATE(DISTINCTCOUNT(TABLE1[REFERENCE_NUMBER];TABLE1[IS_CASE_CLOSED])=1))
#Total Offered is presented by CREATION_YEAR_MONTH_NUMBER
#Handled is presented by CURRENT_CASE_STAGE_YEAR_MONTH_NUMBER
I would like to do it as presented below:
Do you have any idea how to solve the case?
Can you try this below 2 Measure? If your coulmn is_case_handled contain always 0 and 1 properly, these simple below measures should work for you.
total_offered = count(your_table_name[is_case_closed])
total_handled = sum((your_table_name[is_case_closed]))

Power BI - totals per related entity

Basically, I’d like to get one entity totals, but calculated for another (but still related/associated!) entity. Relation type between these entities is many-to-many.
Just to be less abstract, let’s take Trips and Shipments as mentioned entities and Shipments’ weight as a total to be calculated.
Calculating weight totals just per each trip is pretty easy task. Here is a table of Shipments weights:
We place them into some amounts of trucks/trips and get following weight totals per trip:
But when I try to show SUM of Trip weight totals (figures from 2nd table) per each related Shipment (Column from 1st table), it becomes much harder than I expect.
It should look like:
And I can’t get such table within Power BI.
Data model for your reference:
Seems like SUMMARIZE function is almost fit, but it doesn’t allow me to use a column from another table than initialized in the function:
Additional restrictions:
Selections made by user (clicks on cells etc.) should not affect calculation anyhow.
The figures should be able to be used in further calculations, using them as a basis.
Can anyone advise a solution? Or at least proper DAX references to consider? I thought I could find a quick answer in DAX reference guide on my own. However I failed to find a quick answer.
Version 1
Try the following DAX function as a calculated column inside of your shipments table:
TripWeight =
VAR tripID =
RELATED ( Trips[TripID] )
RETURN
CALCULATE (
SUM ( Shipments[ShipmentTaxWeightKG] );
FILTER ( Shipments; RELATED ( InkTable[TripID] ) = tripID )
)
The first expression var tripID is storing the TripID of the current row and the CALCULATE function gets the SUM of all of the weight for all the shipments that belong to the current trip.
Version 2
You can also create a calculated table using the following DAX and create a relationship between the newly created table and your Trips table and simply display the weight in this table:
TripWeight =
GROUPBY (
Shipments;
Trips[TripID];
"Total Weight KG"; SUMX ( CURRENTGROUP (); Shipments[ShipmentTaxWeightKG] )
)
Version 3
Version 1 and 2 are only working if the relationship between lnkTrip and Shipment is a One-to-One relationship. If it is a many-to-one relationship, the following calculated column can be created inside of the Trips table:
ShipmentTaxWeightKG by Trip = SUMX(RELATEDTABLE(Shipments); Shipments[ShipmentTaxWeightKG])
hope this helps.

Filtering other tables based on cross-highlighting a filtered measure

I want to count records in a certain condition and allow people to filter down to the relevant records, but selecting a measure value (which filters so it only counts certain rows) isn't cross-filtering others as I'd expect. Maybe ths isn't possible or maybe I'm just doing it wrong, but I'd appreciate help.
I have a single table:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45Wci4tLsnPTS1SMFTSUTJUitVBEjICChmgChljCplgajSFCMUCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [#"Customer Name" = _t, #"Ordered Recently" = _t]),
#"Change to INT" = Table.TransformColumnTypes(Source,{{"Ordered Recently", Int64.Type}}),
#"Change to T/F" = Table.TransformColumnTypes(#"Change to INT",{{"Ordered Recently", type logical}})
in
#"Change to T/F"
The result looks like this:
Customer Name Ordered Recently
Customer 1 True
Customer 2 False
Customer 3 False
Customer 4 True
Customer 5 True
I added two measures:
Count Total = COUNTROWS(Customers)
Count Recent = CALCULATE([Count Total], filter(Customers, Customers[Ordered Recently]))
If I put both measures in a bar chart and highlight the "Count Recent" measure, I'd expect it to know to filter other visuals based on the FILTER statement present in the measure, but that doesn't happen. Selecing this value doesn't impact anything else on my page (including just a count of rows).
The goal is to allow people to select a measure that counts rows and then to see the makeup of the data in those rows (select a count of late projects and filter other visuals to describe those late projects).
Is this possible or am I doing something wrong?
EXAMPLE:
Here's what it looks like now, with nothing selected:
When I select the black bar (the "Ordered Recently" measure), nothing changes right now - but here's what I want to happen (actually achieved with a slicer off screen on the T/F field):
I understand if my measure is a SUM of an integer field, it includes every row in the calculation - even when the row value is zero - and there's no way to filter my dataset based on that. However, in this case, my measure is actually using a FILTER on the dataset so that it only counts rows with a certain criteria set - given that, it should be able to filter the requested table, and then flow that filter through the rest of my dataset (the same way it would if I selected a bar from a chart where I had used that same field as the series - exactly how it works when I do this:
PBIX file to download as an example
No, I don't believe it's possible to make a measure value cross-filter other visuals based on filters within the measure definition.
You can, however, click on i.e. row header Customer 3 and it should cross-filter the other visuals to only include that customer. Any table column you set for the rows or columns of a matrix visual should behave this way.
Here's a hacky workaround:
Create a measure that shows the right values when you use the column you want to use as a filter as the Legend or Axis (like in your last image). For example, in this case, you could do this:
Total Customers =
VAR TF = SELECTEDVALUE ( Customers[Ordered Recently] )
RETURN
COUNTROWS (
FILTER (
ALLSELECTED ( Customers ),
IF ( TF, TF, TF || Customers[Ordered Recently] )
)
)
This behaves how you want, but isn't labeled as you want. To achieve that create a calculated column with the labels you want. For example,
Label = IF(Customers[Ordered Recently], "Ordered Recently", "Total Customers")
Then take Ordered Recently off the axis and put the Label column in the Legend box to get this:
Your Filter argument is really Filter(All(Customers, Customers[Ordered Recently])
You remove all filters on the Customer Table, and then specify Ordered Recently Column as the filter.
Try
[MeasureName] =Calculate([Count Total], All(Customer), Values(Customer[Recently Ordered]), Customer[Recently Ordered] = “True”)