Measure Including Year Filter - powerbi

i have done a Measure to get the Revenue from TOP N Products.
N depends on the selected Value from my TOP-N Table (It's containing just the numbers from 1 to 10).
In the same Measure, I also calculate how much was the revenue of all Products how were not in the selected Top N.
The Code for this is:
Top N Produktbez Sum DB3 =
VAR TopNSelected =
SELECTEDVALUE ( 'TOP N-Filter'[TOP N] )
VAR TopNProdbezTable =
TOPN ( TopNSelected, ALLSELECTED ( 'Pseudo Produkbez Table' ), [DB3] )
VAR TopNProdbez =
CALCULATE ( [DB3], KEEPFILTERS ( TopNProdbezTable ) )
VAR OtherSales =
CALCULATE ( [DB3], ALLSELECTED ( 'Pseudo Produkbez Table' ) )
- CALCULATE ( [DB3], TopNProdbezTable )
VAR CurrentProd =
SELECTEDVALUE ( 'Pseudo Produkbez Table'[Produktbezeichnung] )
RETURN
IF ( CurrentProd <> "Others", TopNProdbez, OtherSales )
Now I want to add Year as Filter.
I'm using the Year coming from the Date Hierarchy.
Unfortunately, I can't provide a sample yet.
If a sample is need, I will try to create own.

Related

How to calculate the average of multiple categories in Power-BI DAX?

I have a table with the following columns:
Industry table
Industry_ID Score
1 2
1 3
2 2
2 4
3 0
4 2
I need to calculate the average of each industry and then the average of those averages.
Like avg of scores of
1=(2+3)/2 =>2.5
2=(2+4)/2 =>3
3=0/1 => 0
4=2/1 => 2
Then average of these averages, i.e (2.5+3+0+2)/4 => 1.85
The tables are in direct query so please consider that. Any help is appreciated. Thank you
For creating the average of distinct values, create a calculated column as:
Average =
var no_ID = 'Table'[Industry_ID]
Return
AVERAGEX(
FILTER(ALL('Table'), 'Table'[Industry_ID] = no_ID),
'Table'[Score]
)
This will give you a column having average of distinct Industry_ID.
For creating an average of averages, create a measure as:
Measure = AVERAGEX(SUMMARIZE('Table', 'Table'[Industry_ID], 'Table'[Average]), 'Table'[Average])
Final Output-
Here are 2 ways to achieve that:
Just switch between Individual and Overall Average variables in the RETURN part, also store this code CALCULATE ( COUNTROWS ( Industry ) ) in a separate measure so that it can be re-used in various places without making the code verbose
Industry Average =
VAR AllIndustryAverages =
AVERAGEX (
ALL ( Industry[IndustryID] ),
DIVIDE ( [Total Score], CALCULATE ( COUNTROWS ( Industry ) ) )
)
VAR IndividualAverages =
AVERAGEX (
VALUES ( Industry[IndustryID] ),
DIVIDE ( [Total Score], CALCULATE ( COUNTROWS ( Industry ) ) )
)
RETURN
IndividualAverages
Industry Average 2 =
VAR VisibleIndustries =
VALUES ( Industry[IndustryID] )
VAR AllIndustryAverages =
ADDCOLUMNS (
ALL ( Industry[IndustryID] ),
"Average",
VAR CurrentIndustryTotalScore = [Total Score]
VAR IndustryCount =
CALCULATE ( COUNTROWS ( Industry ) )
RETURN
DIVIDE ( CurrentIndustryTotalScore, IndustryCount )
)
VAR IndividualAverages =
AVERAGEX (
FILTER ( AllIndustryAverages, Industry[IndustryID] IN VisibleIndustries ),
[Average]
)
VAR OverallAverage =
AVERAGEX ( AllIndustryAverages, [Average] )
RETURN
IndividualAverages

How to calculate rank within Sales ranges

How to calculate rank within Category defined on sales level. Say, that we want to label products with Sales above some threshold with Category "high", and below that threshold with Category "low".
Here is a sample data.
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcisqzSwpVtJRSiwoyEkF0oZKsTpIwkmJeUAIZJigipfn56QlpRYVVQLZpqhSyRlQcWOweFhqempJYlJOKlgusagovwS7XEF+SWJJPtwJKHL5eZn5eUDaHNUqHI5GdkEsAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Category = _t, Product = _t, Amount = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Amount", Int64.Type}})
in
#"Changed Type"
My question is a nephew related to its older uncle, who now I want to call in:
Percent Rank within Category =
VAR HasOneValueTrue = HASONEVALUE ( MyTable[Product] )
VAR tbl =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
REMOVEFILTERS ( MyTable[Product] ),
VALUES ( MyTable[Category] )
)
VAR result =
CALCULATE (
DIVIDE (
RANKX (
tbl,
[Sales],
,
ASC
) - 1,
COUNTROWS ( tbl ) - 1
)
)
RETURN
IF (
HasOneValueTrue,
result
)
The difference is that the uncle has Category defined in table column, but now we want to have category calculated on the fly based on sales level. So I tried
replacing the VAR tbl code with the following one with the threshold of 4:
var tbl =
SUMMARIZECOLUMNS (
MyTable[Product],
"CalculatedCategory", IF ( [Sales] > 4, "high", "low" ),
"AggSales", [Sales]
)
Nevertheless, I am not able to refer to such defined variable. I also failed with trial based on creating first a DAX table and then trying to refer to it.
Here are expected results:
References
Here is the family of related questions which members I met on the way while approaching to state this problem.
DAX equivalent of Excel PERCENTRANK.INC per category
DAX RANKX for within Category
DAX REMOVEFILTERS vs ALL
The value parameter in DAX function RANKX
DAX ALLEXCEPT to sum by category of multiple dimension tables
This can be done with a minor modification to my answer here. Copied below:
Percent Rank =
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
ALLSELECTED ( MyTable[Product] )
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE ( RankProduct - 1, COUNTROWS ( ProductsInCategory ) - 1 )
)
First, define the calculated category as you suggested.
CalculatedCategory = IF ( [Sales] > 4, "high", "low" )
Then plug that into a filter in the ProductsInCategory variable.
Exp. Results =
VAR CalculatedCategory = [CalculatedCategory] /*Determine current category*/
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = CalculatedCategory /*New Condition*/
)
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE ( RankProduct - 1, COUNTROWS ( ProductsInCategory ) - 1 )
)
Output:
Edit:
To handle the case where there is only 1 product in a category, you can use MAX to disallow a zero value for the denominator.
Exp. Results =
VAR CalculatedCategory = [CalculatedCategory] /*Determine current category*/
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = CalculatedCategory /*New Condition*/
)
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE (
RankProduct - 1,
MAX ( COUNTROWS( ProductsInCategory ) - 1, 1 )
)
)
Being very grateful to Alexis Olson, I would like to share a different solution I ended up with. The solution proposed by Alexis works well in my simple example, but it did not work in my complex model. In my complex model the RANKX function does not give the expected results. RANKX returns the same rankings for different sales values.
For the time being this is the solution that works without figuring out what causes RANKX to return ties for different sales values.
First of all, defining Category measure:
CalculatedCategory =
SWITCH (
TRUE (),
NOT ( HASONEVALUE ( MyTable[Product] ) ), "total", -- important to handle totals
[Sales] <= 4, "low",
[Sales] > 4, "high",
"other"
)
It is important to exclude totals from Category. I did it by setting up a different category for totals. Otherwise totals will fall into "high" category bucket. It would distort final results.
I have not used RANKX in calculation of Percent Rank within Category. I used MIXTURE OF COUNTROWS and FILTER.
PercentRank within Category =
VAR category = [CalculatedCategory]
VAR ProductSales = [Sales]
VAR ProductsMatching =
COUNTROWS (
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = category
&& [Sales] >= ProductSales
)
)
var ProductsAll =
COUNTROWS (
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = category
)
)
RETURN
DIVIDE (ProductsMatching-1, MAX( ProductsAll-1, 1 ))
I calculated rows of two tables. First table ProductsMatching has all products that have sales in appropriate category and sales that are higher or equal of the product. ProductsAll returns number of products in category.

Create measure to calculate % change from distinct values in a column

Situation:
I have a column in my table with values representing weeks of the year.
Each week number has their respective total counts of purchases on another column. When I use a matrix visual and put that specific column in the Columns section it separates them distinctively which is what I want. How can get the % change from one week to another?
Table looks like this:
Objective:
Create a measure that can divides column 2 by column 1 to get the % change.
Layout of Matrix:
Ideally I would like to have a third column to calculate the values in column 6 by the ones in column 5.
OK, here is one solution:
Delta :=
VAR Week5 =
CALCULATE ( SUM ( 'Table'[Total] ), FILTER ( 'Table', 'Table'[Weeks] = 5 ) )
VAR Week6 =
CALCULATE ( SUM ( 'Table'[Total] ), FILTER ( 'Table', 'Table'[Weeks] = 6 ) )
RETURN
IF (
SUM ( 'Table'[Total] ) = SUMX ( ALL ( 'Table' ), 'Table'[Total] )
|| SUM ( 'Table'[Total] )
= SUMX (
FILTER ( ALL ( 'Table' ), 'Table'[Cohort] = MAX ( 'Table'[Cohort] ) ),
'Table'[Total]
),
100*DIVIDE ( Week6 - Week5, Week5 ),
BLANK ()
)
I tested it and it works:
BUT because the way your data is structured, it makes it very difficult (for me) to make this pretty. But hey, it works!! ;) I wasn't sure which direction you needed the delta but that is a simple change in the measure from this:
100*DIVIDE ( Week6 - Week5, Week5 )
To this:
100*DIVIDE ( Week5 - Week6, Week6 )
Hope this help!

Pareto (80/20) Segmentation in Power BI

I created 80/20 segmentation in my Power BI data model and I got what I wanted (see the table below).
Now I want to calculate new Name column with the next logic: if Cumulative % <=80% show value from the "Customer Name" column, otherwise show "Other" (the result will be the column Name as in the table below).
I tried with this calculated column but it doesn't work (the result isn't correct, it's always "Other"):
80/20 Name = IF([Cumulative Percen.] <= 0.8, SalesReport[Names], "Other")
Note: "Cumulative Percen." is calculated measure.
How can I do this?
In the next step, I'll use a pie chart to show this segmentation where all customers with small cumulative transactions will be categorized as Other.
The calculated measures that I used:
Customer Rank by Transaction =
IF (
HASONEVALUE ( SalesReport[CustName] ),
RANKX (
ALLSELECTED ( SalesReport[CustName] ),
CALCULATE ( [# of Transactions] ),
,
DESC,
DENSE
)
)
Customer Cumulative Transaction =
VAR CurrentCustimerRank = [Customer Rank by Transaction]
RETURN
SUMX (
FILTER (
ALLSELECTED ( SalesReport[CustName] ),
CALCULATE ( [Customer Rank by Transaction] ) <= CurrentCustimerRank
),
CALCULATE ( DISTINCTCOUNT ( SalesReport[CustID] ) )
)
Customer Cumulative Transaction Percen. =
[Customer Cumulative Transaction]
/ CALCULATE (
DISTINCTCOUNT ( SalesReport[CustID] ),
ALLSELECTED ( SalesReport[CustName] )
)

How do I calculate the sum of Value for the last 6 sprints using DAX

Problem:
I need a calculated measure in DAX that sums the Value column for the last 6 sprints. I am basing the last 6 sprints on the DimSprintEndDateKey in descending order.
Table structure in PowerBI
The DAX that I am using:
CALCULATE (
SUM ( factSprint[Value] ),
FILTER (
ALL ( factSprint ),
COUNTROWS (
topn(6,
FILTER (
factSprint,
EARLIEST( RELATED ( dimSprint[DimSprintEndDateKey] ) )
> RELATED ( dimSprint[DimSprintEndDateKey] )
),RELATED ( dimSprint[DimSprintEndDateKey] ), DESC
)
)
)
)
I am assuming that the relationship on your tables is between 'dimSprint'[dimSprintKey] and 'FactSprint'[dimSprintKey].
That being the case, this measure could work for you.
Total Value Last Six Sprints =
VAR endDateSprint =
LOOKUPVALUE (
'dimSprint'[dimSprintEndDateKey],
'dimSprint'[dimSprintKey], SELECTEDVALUE ( 'FactSprint'[dimSprintKey] )
)
VAR dimTableFiltered =
FILTER ( 'dimSprint', 'dimSprint'[dimSprintEndDateKey] <= endDateSprint )
RETURN
CALCULATE (
SUM ( 'FactSprint'[Value] ),
ALL ( 'FactSprint' ),
TOPN ( 6, dimTableFiltered, [dimSprintEndDateKey], DESC )
)
Use it on a matrix visual (or pivottable). Be sure to put 'FactSprint'[dimSprintKey] or 'FactSprint'[SprintPK] on Rows and [Total Value Last Six Sprints] on Values.