Power BI - rankx with filter - powerbi

I've been struggling with this and hope someone is able to help...
I have a table with sales for products over multiple years. There is a measure that gives me the total revenue for each year by customer, ignoring product sold:
totalRevenueMeasure =
CALCULATE (
SUM ( test[Revenue] ),
ALLEXCEPT ( test, test[company], test[year] )
)
Year company Product revenue totalRevenueMeasure rankx (revenue in year)
2018 company a shoes 100 300 1
2018 company a mugs 200 300 1
2018 Company b shoes 250 250 2
2019 company a lamps 300 300 2
2019 Company b shoes 350 450 1
2019 Company b mugs 100 450 1
2019 Company c mugs 100 100 3
2020 company a shoes 150 150 2
2020 Company c lamps 200 200 1
The closest I got to the RANKX measure is below but this doesn't give the correct results. The expected output is in the RANKX column of the table above.
Customer Rank =
RANKX(
ALLSELECTED( test[company],test[year]),
[TotalRevenueMeasure],
,
DESC,
Dense
)
Thanks in advance for pointers, DAX is still eluding me a bit and there might be a better way to go about it.
Following the recommendation from Alexis, success with test data but live skips some rows in rank - year 2019 doesn't have a rank #1 but has 2 rank #2. I guess this must be some kind of data issue...

You're very close. The problem is that you are looking to rank each year separately but you've removed the Year filter context with your ALLSELECTED function.
Take out the second argument in ALLSELECTED so that you only have company (since you don't actually want to rank over all years for each row).

Related

Why do i get the avrage of the subcategory and not the avrage of category per year?

When i drag in a tabel
and just have
-YEAR
-Kategory
-Summa
I will get the medium value of 895,50 (815 + 976 / 2) for february
I don't want it to separeate the Subcategory
I want it to show
1791
when i just mark february
and if i use February and March
It sould say
2022 Inköp 2435,5
Becouse that the Medium of February and Marsh on the category
It's difficult to understand what you are asking (likely the reason for your downvotes). I think you are after a monthly average measure. Since your sample data is extremely limited I assume that each month will have exactly one date. Ideally this type of calculation should be handled by using a calendar table as a basis for month values, but for your sample data, try this:
Monthly average =
AVERAGEX (
VALUES ( 'Table'[Datum] ) ,
CALCULATE ( SUM ( 'Table'[Summa] ) )
)

DIVIDE/AVERAGEX in PowerBI

In my data model I have 12 months worth of employee data and month name is in the first column, I.e Jan, Feb Mar etc
I have been using the formula below but I have an issue,
Employee 101 has worked as a sole employee in one department
2 months out of the 12, my formula below will divide that 2/12 equaling =0.16. I want to return average headcount for the department as 1.
So only averaging for months greater 0 employees
DIVIDE(
AVERAGEX(
KEEPFILTERS(VALUES('Date Table'[Month])),
CALCULATE(COUNTROWS(Employee List),Employee List[Emp Status] = "Full Time")),,"")
So use roundup():
roundup(DIVIDE( AVERAGEX( KEEPFILTERS(VALUES('Date Table'[Month])), CALCULATE(COUNTROWS(Employee List),Employee List[Emp Status] = "Full Time")),,""),0)
But you might consider wrapping it in an if() so it only rounds up when the result is less than 1.
I was Averagex and Divide at the same time, removing divide fixed the issue.

Calculate age cluster dynamically in DAX - Power BI

I have created a report for the HR department. One of the visuals aims to display the pyramid of ages of the employees by gender (we take cluster of 5 years, e.g. 20-25 for people between 20 and 25 years old).
To make it simple, data wise, I have a table with the list of employees, including their date of birth and many other fields, not relevant for this post. I added a calculated column with the age cluster based on the today’s date:
AgeCluster =
VAR AgeCalc=if(HR_DATA[Birthdate]=blank(),blank(),DATEDIFF(HR_DATA[Birthdate],today(),YEAR))
VAR Mult5=INT(AgeCalc/5)
RETURN
if(isblank(AgeCalc),blank(),5*Mult5&"-"&5*(Mult5+1))
And I have a basic visual (tornado chart with the AgeCluster in Group, showing male and female)
Now my issue is that my report should be dynamic, so the user should be able to see the situation in the past or in the future... I have a calendar table (not linked to my HR_Data table), and a date slicer on my report's page. I need the age cluster to be recalculated.
I have tried a calculated table, but I can’t get it working properly. I have read various blog posts on similar issue, but still can't figure out how to solve it...
Any idea or tips much appreciated.
Thank you so much!
Dynamic filtering usually means in these situations that you need a fixed x-axis to work with. That x-axis is calculated outside the original table, such as a parameter table.
Assuming your data looks like this:
Table: Employees
EmployeeID
DOB
1
20 March 1977
2
05 December 1981
3
25 December 1951
4
20 December 1954
5
04 March 1980
6
24 July 1968
7
07 June 1984
8
01 October 1992
9
25 February 1999
10
02 November 1987
First, we need to create the Age Groups with their respective lower and top bands. This table uses a similar code when a parameter table is created.
Table: Buckets
Because you are using whole numbers, I think is best to calculate the TopBand by adding 4. In that case, you don't have repeating numbers. In other words, ranges shouldn't overlap (20-25 and 25-30)
Buckets =
SELECTCOLUMNS (
GENERATESERIES ( 20, 80, 5 ),
"Age Series",
[Value] & " - " & [Value] + 4,
"LowerBand", [Value],
"TopBand", [Value] + 4
)
Also, we will need a Calendar Table to filter accordingly.
Table: CalendarHR
CalendarHR =
ADDCOLUMNS (
CALENDAR ( MIN ( Employees[DOB] ), TODAY () ),
"Year", YEAR ( [Date] )
)
With all that, you can create a calculation that can be filter dynamically.
DAX Measure:
EmployeesbyBracket =
VAR _SelectedDate =
MAX ( CalendarHR[Date] )
VAR _SelectedLowerBand =
SELECTEDVALUE ( Buckets[LowerBand] )
VAR _SelectedTopBand =
SELECTEDVALUE ( Buckets[TopBand] )
VAR EmployeesAge =
ADDCOLUMNS (
Employees,
"Age",
INT ( DATEDIFF ( [DOB], _SelectedDate, YEAR ) / 5 ) * 5
)
RETURN
COUNTROWS (
FILTER (
EmployeesAge,
[Age] >= _SelectedLowerBand
&& [Age] <= _SelectedTopBand
)
)
Output
I've created a table visual with the Age Groups from the Buckets table.
Both a calculated column and a calculated table will be static and not achieve your desired objective. You need age to be calculated via a measure.
Create a disconnected table with your age buckets and then implement the dynamic segmentation pattern.

Power Bi Super slow Query needs a performance boost

Our Subscription table is contains around 40k entries. I am trying to calculate the Monthly-Recurring.Dim is a simple calendar table to map the date ranges start and end to the days.
Sumx('Subscription Clean',
CALCULATE(
SUMX(
SUMMARIZE(
FILTER(
CROSSJOIN(
'Subscription Clean',Dim
),
Dim[Date] <= 'Subscription Clean'[End At] &&
Dim[Date] > 'Subscription Clean'[Start At]
),
'Subscription Clean'[Duration total],
'Subscription Clean'[Duration],
'Subscription Clean'[End At],
'Subscription Clean'[Start At],
'Subscription Clean'[Price]),
DIVIDE(DIVIDE(
'Subscription Clean'[Price],DATEDIFF([Start At],[End At],DAY)+1
),1.19) % Tax of 19
)
)
)
The data looks like this
Sales Id
Product name
created At
end at
Cancelled At
Price in €
Duration
1
bananas
01.01.2021
01.03.2021
28.02.2021
20.00
2
2
apples
01.02.2021
01.05.2021
null
90€
3
The output should be like this for the mmr each month 10€ come from the first position for the months {1,2}
Each price will be distributed between the dates Start and End.
jan = 10
feb = 40
mar = 30
apr = 30
may = 0
The DAX query is working properly but hell a slow. Is there any way to improve the performance? Further the calculated measure will be used to do more calculations and needed to be loaded in memory if possible for quick access. Maybe anyone knows how to do it properly and I can leech some good hints ;)

Calculate monthly value between 2 tables without an explicit relationship in Power BI model

I am trying to create a measure that calculates (a/qty)*100 for each month,
where qty commes from Delivery table (generated with an R script)
month qty
<date> <dbl>
1 2019-02-01 1
2 2019-03-01 162
3 2019-04-01 2142
4 2019-05-01 719
And a comes from a table TABLE_A that has been created within Power BI that looks like this :
Client Date a
x 2019-03-07 3
x 2019-04-14 7
y 2019-03-12 2
So far, I managed to calculate that value overall with the following measure formula :
MEASURE = CALCULATE( (Sum(TABLE_A[a])/sum(Delivery[qty]))*100)
The issue I have is that I would need this measure monthly (i.e. join the tables on month) without explicitly defining a link between the tables in the PowerBI model.
For each row in TABLE_A you need to look up the corresponding qty in Delivery, so try something along these lines:
MEASURE =
DIVIDE(
SUM( TABLE_A[a] ),
SUMX(
TABLE_A,
LOOKUPVALUE(
Delivery[qty],
Delivery[month], EOMONTH( TABLE_A[Date], -1 ) + 1
)
)
) * 100
The formula EOMONTH( TABLE_A[Date], -1 ) returns the end of the previous month relative to that date and adding 1 day to that to get the start of the current month for that date.