Year over Year Variance Calculation Error "EARLIER/EARLIEST" refers to an earlier row context which doesn't exist - powerbi

While trying to calculate Year over Year variance (unsuccessfully for 2 days now), I get the following error message.
EARLIER/EARLIEST refers to an earlier row context which doesn't exist.
YOY Variance = var PreviousYearPrinBal = CALCULATE(SUM(Deals[Principal Balance]),FILTER(ALL(Deals[Close Date].[Year]),Deals[Close Date].[Year] = EARLIER(Deals[Close Date].[Year])))
return
if(PreviousYearPrinBal = BLANK(), BLANK(), Deals[PrincipalBalance] - PreviousYearPrinBal)
In a different SO question, there is a different approach which gives me the following error:
A column specified in the call to function 'SAMEPERIODLASTYEAR' is not of type DATE. This is not supported.
yoy = CALCULATE([PrincipalBalance], SAMEPERIODLASTYEAR(Deals[Close Date].[Year]))
While I have some idea of what these mean, I do not have an idea of how to fix them. Here is my table.
And Here is what I expect as the result.
I've tried posting this question in Power BI community but haven't received an answer yet. Calculate Year over Year Variance.
ACTUAL DATA SAMPLE:

1) Created Year and Year Difference Column (Calculated Column)
Year = YEAR(Table1[Date])
Year Difference = Table1[Year] - Min(Table1[Year])
2) Created the Variance (Measure)
Variance =
Var current_YearDifference = SELECTEDVALUE(Table1[Year Difference])
Var Current_PrincipalBalance = CALCULATE(SUM(Table1[Principal Balance]),FILTER(ALL(Table1), Table1[Year Difference] = (current_YearDifference)))
Var Previous_PrincipalBalance = CALCULATE(SUM(Table1[Principal Balance]),FILTER(ALL(Table1), Table1[Year Difference] = (current_YearDifference - 1)))
Return if(current_YearDifference <> 0, (Current_PrincipalBalance - Previous_PrincipalBalance), 0)
3) Finally Created the Variance in terms of Percentage (Measure),
Variance in terms of Percentage =
Var current_YearDifference = SELECTEDVALUE(Table1[Year Difference])
Var Current_PrincipalBalance = CALCULATE(SUM(Table1[Principal Balance]),FILTER(ALL(Table1), Table1[Year Difference] = (current_YearDifference)))
Var Previous_PrincipalBalance = CALCULATE(SUM(Table1[Principal Balance]),FILTER(ALL(Table1), Table1[Year Difference] = (current_YearDifference - 1)))
Return if(current_YearDifference <> 0, ((Current_PrincipalBalance - Previous_PrincipalBalance) / Previous_PrincipalBalance), 0)
My Final Output
The Principal Balance has the function SUM selected on the Values Pane of the Output Table, where as the Year is Don't Summarize.
My Best Practice
Always Use Vars when creating Complex Measures to simplify the
formula.
Then return only a part of the Measure to check if the output is as expected.
Kindly let me know, if it helps or not.

Related

ABC analysis without aggregation

I never use DAX and I find it very complicated!
I read this https://www.daxpatterns.com/abc-classification/ but I find it complicated.
My dataset is like this https://1drv.ms/x/s!AvMy-Bzzx3mqgwmKSZm6wr_W4VXr?e=Jwwbji&nav=MTVfezAwMDAwMDAwLTAwMDEtMDAwMC0wMDAwLT...
I need to sum column Value if the Name and date are the sums after doing the ABC analysis. The problem is that I can't aggregate before in transform because I need the column Name Fatt!
It is not necessary for a dynamic ABC analysis. The value for each Name and Date is the same...
I appreciate every help! Also video tutorial or something can help me. Thanks!
'Aggregazione fatturato = SUMX(UNION(VALUES(Name),VALUES(Date)),SUM(Value)
Fatturato Cumulato =
VAR CurrentProductSales = 'Misure'[Aggregazione fatturato]
VAR BetterProducts =
FILTER (
Name,
'Misure'[Aggregazione fatturato] >= CurrentProductSales
)
VAR Result =
SUMX (
BetterProducts,
'Misure'[Aggregazione fatturato]
)
RETURN
Result
Cumulated Pct =
DIVIDE (
'Misure'[Fatturato Cumulato],
SUM ('Misure'[Aggregazione fatturato])
ERROR 'Misure'[Aggregazione fatturato] not found

calculate the days between the first and second purchase for each user

How can I calculate the time interval(days) between the first and second purchase for each user who has more than one order in Power BI? The second purchase which I want doesn't have the same order date as the first order.
for example, see this sample data:
result for this example should be the same as this pic:
I'm not familiar with M programming("let" and "in"). Please give me a solution that doesn't have M code.
Do this with a measure:
Result_day =
var __atleast2day = COUNTROWS(OrdTab)
var __dynam = TOPN(2, CALCULATETABLE(OrdTab), OrdTab[order_date], ASC)
var __first = maxx(__dynam, OrdTab[order_date])
var __second = minx(__dynam, OrdTab[order_date])
var __result = if(__atleast2day >1, __first - __second, 0)
return
__result
here sample;
Use the following code to get exact result

Implementing Binomial Hypothesis Testing significance tests in Power BI (DAX)

This is partly a theory question, and partly an implementation question. My stats is a little rusty...
I am developing a report that is attempting to determine if the difference in occurances between a reference group and a selected group are statistically significant.
So, for example, if something occurs in X of n tests for one group, is it statistically significant than if it 'normally' occurs at a rate of Y of m tests for a different (control) group.
So, my H0 is that the rate is Y of m, per the control group
h1 is that it is not the same as the control group. (ideally, I'd like to use a 1-tailed test, depending if the observed occurrence is greater or less than the control, but my current implementation is 2 tailed)
I'd be comfortable with a CI of 80%.
I've got (slightly pseudocode here):
Zscore =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
VAR pTest = DIVIDE(COUNT([Test occurrences]), COUNT([Test Tests])) RETURN
VAR controlStandardError =
SQRT(
DIVIDE(
(pControl * (1-pControl)
, COUNT([Control Tests])
)
) RETURN
VAR testStandardError =
SQRT(
DIVIDE(
(pTest* (1-pTest)
, COUNT([Test Tests])
)
) RETURN
DIVIDE(
(pTest - pControl)
, SQRT(POWER(testStandardError, 2) + POWER(controlStandardError, 2)
)
I'm then calculating:
p-Value =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
IF(pControl > 0,
1 - ABS(NORM.DIST(Zscore, 0, 1, TRUE)
)
I am then displaying in a table each of my non-null hypotheses and filtering the table such that p-Value is less than 0.1. (2-tailed 80%)
am I on the right track here? Or have I completely bungled the theory on this one?
Theory and example tables - Right-tailed (μ > μ₀)
DAX
ControlGroup
XControl = COUNTROWS(FILTER(ControlGroup,ControlGroup[Outcome]=1))
NControl = COUNTROWS(ControlGroup)
pControl = DIVIDE([XControl],[NControl])
TreatmentGroup
XTreatment = COUNTROWS(FILTER(TreatmentGroup,TreatmentGroup[Outcome]=1))
NTreatment = COUNTROWS(TreatmentGroup)
pTreatment = DIVIDE([XTreatment],[NTreatment])
Test Parameters
PooledProportion =
DIVIDE(
[XTreatment]+[XControl],
[NTreatment]+[NControl]
)
ZCritivalValue = NORM.S.INV(0.90)
ZValue = DIVIDE(
[pTreatment]-[pControl],
SQRT(
[PooledProportion]*(1-[PooledProportion])*((1/[NTreatment])+(1/[NControl]))
)
)
Visualization (example)

LOOP to Look up the value in M Query

I have a following data table:
I need to create a column called FINAL VALUE with certain rules in the power query editor:
The FINAL VALUE is created based on the COUNTRY
If VALUE is greater than 100, then the previous value will be taken
if the previous values (no previous value such as 202001) are all greater than 100, then 100
So the final table should look like:
I sort COUNTRY and DATE, and then I try to apply loop in M Query. As I am not familiar with the function in M query, I have hard time figuring out. I appreciate any help. Thank you.
I believe you are better of in DAX. You can create a new column like below:
Final Value =
var curCountry = TableCountry[Country]
var curDate = TableCountry[Date]
var prevDate = CALCULATE(MAX(TableCountry[Date]), FILTER(TableCountry, curDate >= TableCountry[Date] && curCountry = TableCountry[Country] && TableCountry[Value] <=100))
return LOOKUPVALUE(TableCountry[Value], TableCountry[Country], curCountry, TableCountry[Date], prevDate, 100)

Google Sheets - formula for expense sheet

I need a formula that will help me calculate the $ expense amount for my milage rates.
Here is my sheet https://docs.google.com/spreadsheets/d/1PPFuFWbxWi9iIdtYBJvnSNB1j1cjjQutepF3hnpGoFM/edit?usp=sharing
On the tab that's expenses, I need to check the year of my date in Col A (because different years have different rates), then check Col D to see if it says Milage, then check Col E for what type of milage (there are 4 types), then return the number input in Col I times the appropriate rate for that year and type of milage. I have a table set up with the rates in another tab.
I'm thinking it will be a long IF and AND formula. Any help would be great!
In 'Essentials Log', I've changed the format of your year start-end dates to state the year you're referencing. I've added a column for "Milage".
Expense Reference Screenshot
In 'Expenses'!M2, I tried this and it seems to work:
=ARRAYFORMULA(iferror(if(isblank(A2:A),"",I2:I*vlookup(D2:D&year(A2:A)&E2:E,query({'Essentials Log'!Y2:Y&'Essentials Log'!Z2:Z&'Essentials Log'!AA2:AA,'Essentials Log'!AB2:AB},"Select *"),2,false))))
Working Example Screenshot
Have a look (I copied your example sheet): Milage expense
I solved this with creating an app script.
I realized I didn't want to use a formula because in my $ col most entries will be keyed in and so I didn't want to copy and paste a formula every time.
Here is the code if anyone might need it. I added it to the menu so the calculation is done with a click.
function expenseMilageCalculation() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var expensesTab = auditionsSheet.getActiveSheet();
var activeCell = expensesTab.getActiveCell();
var activeRow = activeCell.getRow();
var expenseDate = expensesTab.getRange(activeRow, 1).getValue();
var expenseYear = expenseDate.getFullYear();
var expenseType = expensesTab.getRange(activeRow, 4).getValue();
var expenseDetails = expensesTab.getRange(activeRow, 5).getValue();
var numMiles = expensesTab.getRange(activeRow, 9).getValue();
var essentialsLogTab = auditionsSheet.getSheetByName("Essentials Log")
//2018 Business Milage
if (expenseYear == 2018 && expenseType == "Milage" && expenseDetails == "Business") {
var milageBusinessRate2018 = essentialsLogTab.getRange(3, 27).getValue();
var dollarMilesDeduction = numMiles * milageBusinessRate2018
expensesTab.getRange(activeRow, 8).setValue(dollarMilesDeduction)
}
//2019 Business Milage
if (expenseYear == 2019 && expenseType == "Milage" && expenseDetails == "Business") {
var milageBusinessRate2019 = essentialsLogTab.getRange(8, 27).getValue();
var dollarMilesDeduction = numMiles * milageBusinessRate2019
expensesTab.getRange(activeRow, 8).setValue(dollarMilesDeduction)
}