Power BI: Is there a way to get the a value based on the MAX date? - powerbi

I am trying to make a calculated column in Power BI to return the last Job Title held for the name listed based on the maximum/latest date.
Current Title = VAR MaxDate =CALCULATE (MAX('Terms FY23'[Employee History.Date])) VAR EEID = CALCULATE(MAX('Terms FY23'[Employee History.Employee]))RETURN CALCULATE(FIRSTNONBLANK(SELECTCOLUMNS(FILTER('Terms FY23','Terms FY23'[Employee History.Date] = MaxDate && 'Terms FY23'[Employee History.Employee] = EEID),"JobTitle",'Terms FY23'[Employee History.Title]),_MaxDate))
I tried this but it returned the same exact Job Title column.
Date Full Name Job Title
10/31/2022 John Adams Landscaper I
11/30/2022 John Adams Crew Leader
12/31/2022 John Adams Crew Leader
1/31/2023 John Adams Crew Leader
2/15/2023 John Adams Crew Leader

For you sample data this one works
Last Job Title =
VAR MAXDATE =
MAXX('Table', 'Table'[Date])
RETURN
CALCULATE(
MAX('Table'[Job Title]),
FILTER(
ALL('Table'),
'Table'[Date] = MAXDATE
)
)

In case you have more than one distinct name in the table can go via this
calculated table
Lookup Table =
SUMMARIZE(
'Table',
'Table'[Full Name],
"Last Job Titel", CALCULATE(
MIN('Table'[Job Title]),
'Table'[Date] = MAX('Table'[Date])
)
)
to end up with this calulated column
Last Job Title=
LOOKUPVALUE(
'Lookup Table'[Last Job Titel],
'Lookup Table'[Full Name], 'Table'[Full Name]
)

You can add a calculated column that does this directly using the new INDEX windowing function as a filter argument, that uses ALLEXCEPT on your table to provide the correct row context:
Last Title =
CALCULATE (
SELECTEDVALUE ( 'Terms FY23'[Employee History.Title] ),
INDEX (
1,
ALLEXCEPT ( 'Terms FY23', 'Terms FY23'[Employee History.Name] ),
ORDERBY ( [Employee History.Date], DESC )
)
)
This type of calculation would normally require to store the maximum date value first, and then solve for the title:
Last Title Old =
VAR _max_date =
CALCULATE (
MAX ( 'Terms FY23'[Employee History.Date] ),
ALLEXCEPT ( 'Terms FY23', 'Terms FY23'[Employee History.Name] )
)
RETURN
CALCULATE (
SELECTEDVALUE ( 'Terms FY23'[Employee History.Title] ),
ALLEXCEPT ( 'Terms FY23', 'Terms FY23'[Employee History.Name] ),
'Terms FY23'[Employee History.Date] = _max_date
)
NB! If you have two people in this table with the same name, you are out of luck. You would need a more robust way of handling employees, for example by using a unique employee ID instead of some arbitrary name.

Related

Count the number of occurrences after associated date of certain value in Power BI

I'm conducting an exercise around examining test results after tutoring has occurred. Essentially looking at the rates of "pass" post tutoring within the context of a given student. Where the ultimate outcome would be:
pass rate after tutoring = [count passes]/[count test date] WHERE test date > tutoring date.
For example:
Ideally, the final output of the measure would be = 1 (1/1)
Would anyone be able to point me in the direction of achieving this through a Power BI measure?
I've attempted the following to get the single oc with no luck:
Measure 3 = CALCULATE(COUNT(Table[Test Pass?]),FILTER(Table,Table[Test Date]>CALCULATE(Min(Table[Tutoring Date]),FILTER(Table,Table[Tutor (?)] <> BLANK ))))
Where I would then use the student column in a matrix with the measure to group pass rates post tutoring by student
I have used this simple flat table data model:
You can calculate this with a measure that needs to be evaluated with your Student column:
Pass Rate After Tutoring =
VAR _tutor_date =
CALCULATE (
MAX ( 'Table'[Tutoring Date] ),
ALLEXCEPT ( 'Table', 'Table'[Student] )
)
VAR _tests_post_tutor =
CALCULATE (
COUNTROWS ( 'Table' ),
ALLEXCEPT ( 'Table', 'Table'[Student] ),
'Table'[Test Date] > _tutor_date
)
VAR _successes =
CALCULATE (
COUNTROWS ( 'Table' ),
ALLEXCEPT ( 'Table', 'Table'[Student] ),
'Table'[Test Date] > _tutor_date,
'Table'[Test Pass]
)
RETURN
DIVIDE ( _successes, _tests_post_tutor )
But this assumes that students are only tutored for one specific test, and are tutored once.

Running total with a slicer in Powerbi

I am trying to find the running total by month, it worked using the following measure but only without using a slicer for the category "BLK":
With Date = VAR MaxDate =
MAX ( 'Calendar Table'[Date] ) RETURN
CALCULATE (
SUM ( 'Injuries'[Total] ),
FILTER (
ALL ( 'Injuries'[Classification] ),
'Injuries'[Classification] = "FAC"
),
FILTER ( ALLSELECTED ( 'Calendar Table' ), 'Calendar Table'[Date] <= MaxDate)
)+0
The result was only accurate when I don't apply the Category slicer "BLK", I tried a different measure:
With BLK = CALCULATE( SUM('Oxy Oman Personal Injuries'[Total]),
FILTER (
ALL ( 'Injuries'[Classification] ),
'Injuries'[Classification] = "FAC"
), ALLSELECTED('Blocks'[BLK]) )+0
The above gave me something similar to the actual data, it did not sum up the numbers.. at least it gave me the correct total of a the category selected = 5 while the first measure gave the total wrong = 4.
Here is a screenshot of the results for both measures with and without a slicer:
Without BLK slicer:(With Data gave me what I wanted)
Using one Category in the BLK Slicer:
How can I fix that?

Search on value (number) to find text string PowerBI

I work with warranty claims and got two sheets with different suppliers, priority and prices for different part numbers for our product.
One sheet with prices/suppliers is used for our repairs in Asia and other sheet is used for the rest of the world (WW)
Sheet 1: PN-List Asia
Sheet 2: PN-List WW
I've managed to make an IF-statement that find the right price, from the right list (PPU).
The formula I've used:
Price Per unit (PPU) =
IF (
SELECTEDVALUE ( 'Regress List'[Continent] ) = "Asia",
CALCULATE (
MAX ( 'PN-List Asia'[Price Per Unit] ),
FILTER ( 'PN-List Asia', 'PN-List Asia'[Prio] = MIN ( 'PN-List Asia'[Prio] ) )
),
CALCULATE (
MAX ( 'PN-List WW'[Price Per Unit] ),
FILTER ( 'PN-List WW', 'PN-List WW'[Prio] = MIN ( 'PN-List WW'[Prio] ) )
)
)
Now I need to get the suppliers name of the product/item, into my matrix in PowerBI.
Suppliers name can be found in the two different sheets (PN-List Asia & PN-List WW) under supplier name ('PN-list WW'[supplier name]).
My guess is that I need to use an IF statement to decide if I should search in PN-List Asia or PN-List WW, but I'm not sure how to find the right supplier name with Priority (prio) and/or Price Per Unit (PPU).
Answer to #Mik
Funny enough, I should be able to make an export (to excel) from PowerBI, that looks like this:
So I can know who to invoice for all the costs. If the supplier wants more information, we will have it in our PowerBI-matrix.
What if you change your visual, for example, like this? I mean getting of supplier name through measure.
used measures
Price Per unit (PPU) =
VAR partNo = SELECTEDVALUE('Claims List (Monthly refilled'[Used Part ])
VAR priority =
CALCULATE(
MIN('PN-List (static)'[Priority])
,TREATAS({partNo},'PN-List (static)'[Part no])
)
RETURN
CALCULATE(
SELECTEDVALUE('PN-List (static)'[Price Per Unit])
,TREATAS({partNo},'PN-List (static)'[Part no])
,'PN-List (static)'[Priority]=priority
)
Supplier =
VAR Usedpart = VALUES('Claims List (Monthly refilled'[Used Part ])
RETURN
CALCULATE(
SELECTEDVALUE(
'PN-List (static)'[Supplier name]
,IF(
ISBLANK(DISTINCTCOUNT('PN-List (static)'[Supplier name]))
,BLANK()
,"- " & DISTINCTCOUNT('PN-List (static)'[Supplier name]) & " Suppliers")
)
,TREATAS(Usedpart,'PN-List (static)'[Part no])
)

Calculate Current and Previous month's Value based on slicer selection in power bi

I have two tables called
Main Table contains the following data(Pic) and
Date table created using the dates from the Main table.
I want to calculate two fields/measures based on Date slicer selection from the Date Table
current month's revenue
previous month's revenue
Example: If I selected the 4th Month then it should sum distinct revenue of client A and B for the 4th month as current_month_revenue and Sum distinct revenue of A and B for 3rd month as previous_month_revenue.
I tried writing the following Measure to Calculate current_month_revenue and it is working fine but it is not giving the correct result for Previous_month_revenue.
I am getting the same value for the Previous month as well.
'Measure Previous Month Revenue' =
IF (
ISFILTERED ( 'Date'[Year_Month] ),
VAR myTable =
SUMMARIZE (
'Main Table',
'Main Table'[ClientName],
'Main Table'[Mon],
'Main Table'[Revenue]
)
RETURN
CALCULATE (
SUMX (
myTable,
'Main Table'[Revenue]
),
FILTER (
'Main Table',
'Main Table'[Mon]
= SELECTEDVALUE ( 'Date'[Month] - 1 )
)
),
VAR myTable =
SUMMARIZE (
'Main Table',
'Main Table'[Revenue],
'Main Table'[Mon],
'Main Table'[Revenue]
)
RETURN
SUMX (
FILTER (
myTable,
'Main Table'[Mon]
= MONTH (
TODAY ()
) - 1
),
'Main Table'[Revenue]
)
)
Desired Output
If 4th month is selected
Current Moth revenue = 100 + 200 = 300
Previous Month = 100+200 = 300
In this case, both are the same but in actual data, revenue is different for each month.
I see from the code that the 'Date' table has a numeric column called Month, that I assume to be of the same type as the Mon column in your 'Main Table'.
Also, since in the 'Main Table' there is no Year, I assume that the Year is not to be considered.
From the slicer over the Date table we can directly get the selected 'Date'[Month] using SELECTEDVALUE(). As default parameter we use the current month obtained by the TODAY() function.
Then we obtain the Previous Month subtracting one from the Selected Month and we can use it to slice the table grouped by CustomerName, Mon and Revenue. Grouping is needed to remove duplicate Revenues for the same customer on the same month and is implemented using SUMMARIZE()
As a final step we can aggregate the 'Main Table'[Revenue] of the filtered and grouped table using SUMX.
'Measure Previous Month Revenue' =
VAR CurrentMonth =
MONTH(
TODAY()
)
VAR SelectedMonth =
SELECTEDVALUE(
'Date'[Month],
CurrentMonth
)
VAR PrevMonth = SelectedMonth - 1
VAR MyTable =
CALCULATETABLE(
SUMMARIZE(
'Main Table',
'Main Table'[ClientName],
'Main Table'[Mon],
'Main Table'[Revenue]
),
'Main Table'[Mon] = PrevMonth,
REMOVEFILTERS( 'Date' )
)
VAR Result =
SUMX(
MyTable,
'Main Table'[Revenue]
)
RETURN
Result
The same code but for the Previus Month calculation can be written for the current month
'Measure Current Month Revenue' =
VAR CurrentMonth =
MONTH(
TODAY()
)
VAR SelectedMonth =
SELECTEDVALUE(
'Date'[Month],
CurrentMonth
)
VAR MyTable =
CALCULATETABLE(
SUMMARIZE(
'Main Table',
'Main Table'[ClientName],
'Main Table'[Mon],
'Main Table'[Revenue]
),
'Main Table'[Mon] = SelectedMonth,
REMOVEFILTERS( 'Date' )
)
VAR Result =
SUMX(
MyTable,
'Main Table'[Revenue]
)
RETURN
Result
A better solution could be implemented setting a relationship between the 'Date' table and 'Main Table'.
Depending on the business requirement, it could be possilbe to use a Date table at the month level granularity, with a YearMonth column instead of Mon, or at the Day level, with a Date column instead of the Mon column.
CALCULATE does not affect variables that you've already defined, so FILTER does nothing to the first SUMX. See this related post for a bit more detail.
I'd suggest writing the measure much more simply. Something like this:
Previous Month Revenue =
VAR PrevMonth =
SELECTEDVALUE (
'Date'[Month],
MONTH ( TODAY () )
) - 1
RETURN
CALCULATE (
SUM ( 'Main Table'[Revenue] ),
'Main Table'[Mon] = PrevMonth
)

Using summarize and userelationship to generate a sum based on a condition

Story:
I have two date columns in my fact table, one is for orderdate and the second is for orderdate/refund/cancelled date.
I created two relationships between the date table and the fact table.
Active: Date > OrderDate
Inactive: Date > OtherDate
I would like to sum the # of refunds per day using the inactive relationship.
What I tried:
Returns =
VAR summary =
SUMMARIZE (
FILTER ( Query1, Query1[kind] = "refund" ),
Query1[orderId],
"returns", MAX ( Query1[amount] )
)
RETURN
CALCULATE (
MAX ( Query1[amount] ),
USERELATIONSHIP ( Query1[OtherDate], DateTable[Date] ),
summary
)
For some reason, it's using the active date column. Any suggestion on how to fix the above formula?
I'm not sure I understand how you are intending to use the summary variable here, but note that USERELATIONSHIP doesn't affect it at all since it's already computed.
You might not need that variable at all. Try this:
Returns =
CALCULATE (
MAX ( Query1[amount] ),
USERELATIONSHIP ( Query1[OtherDate], DateTable[Date] ),
Query1[kind] = "refund"
)