Power BI Calculated Column based on max date and a filter - powerbi

I have a table that looks as follows:
I am trying to do a calculated column, so that it is 1 when Attribute 1 is 'Actual' and is at the latest available date (eg 3 Nov in this example). The following DAX calculated column does not work, would anyone know why?
LastDateFilter =
VAR MaxDate =
CALCULATE (
MAX ( 'Table'[Date]),'Table'[Attribute 1]="Actual")
RETURN
IF ('Table'[Date] = MaxDate, 1 ,0)

If I understood properly your question, you want a result like the image that you have provided.
I have changed some names and dates but keeping the structure.
This is my approach:
LastDateFilter =
VAR MaxDate =
CALCULATE (
MAX ( 'Tabla'[Date]),FILTER('Tabla','Tabla'[At1]="Actual" && NOT
ISBLANK('Tabla'[At2])))
RETURN
IF (('Tabla'[Date] == MaxDate &&'Tabla'[At1]=="Actual"), 1 ,0)
I put filter for clarify but is not necessary...
If you add data it works:

Related

Why can't I filter a column based on a parameters table's value?

I wanna filter a Date using a table parameters.
First, I created a Parameters table like this :
Here is the table's values :
And then I created a Slicer with the table parameters values as a list :
So what I want is to filter my Date table based on which value is selected on the slicer.
The Date table looks like this :
v_DATE
Date
Date is a "date" type.
Here are some sample values :
Date
13.10.21
14.10.21
15.10.21
The Date table is used on a bar chart with values that came from an article table.
So what I want is when I click on the Last30Days it filters me all the values from the current date to 30 days ago.
I tried this :
On my Date column, I right clicked and clicked on "New measure".
Then I wrote a DAX code like this :
Measure = CALCULATE(IF(SELECTEDVALUE(Parametres[Selection_date]) = "Last30Days", filter(v_Date, v_Date[Date] = "15.10.21")))`
I used 15.10.21 as an example value to test my query. But It didn't work, the date isn't filtered.
So what I am doing wrong ? And how can I write my 3 parameters?
EDIT
How can I add the values that are not in the last 30 days ?
You haven't mentioned the measure/column name which you are applying the filter, so I'm assuming it as a Measure([Measure_Value]).
If your user is only selecting only single option at a time, you can use a switch case to filter the expression based on slicer value.
You can calculate the current date using TODAY() and on the basis of that you can calculate other time values like this:
var _month = MONTH(_today)
var _year = YEAR(_today)
var _last_30_days = _today - 30
On the basis of these values and switch case, you can create the measure:
Measure =
var _today = TODAY()
var _month = MONTH(_today)
var _year = YEAR(_today)
var _last_30_days = _today - 30
return SWITCH(SELECTEDVALUE(Parametres[Selection_date]),
"MonthToDate",CALCULATE([Measure_Value],FILTER(ALL(v_Date),MONTH('v_Date'[Date])=_month && YEAR('v_Date'[Date])=_year)),
"Last30Days",CALCULATE([Measure_Value],FILTER(ALL(v_Date),'v_Date'[Date]>_last_30_days)),
"YearToDate",CALCULATE([Measure_Value],FILTER(ALL(v_Date),YEAR('v_Date'[Date])=_year)),
BLANK())
In your measure formula you need to add the expression that you want to calculate, so if it's a sum or a count of records that's what you pick.
One way of doing it could be:
Measure = Count(Data[Records])
Measure with Param =
var selectedParam = SELECTEDVALUE(Parametres[Selection_date])
var dateFilter = FILTER(Dates,
(selectedParam = "Last30Days" && Dates[Date] = DATE(2021,01,19)) ||
(selectedParam = "MonthToDate" && Dates[Date] > DATE(2021,01,19)) ||
(selectedParam = "YearToDate" && Dates[Date] > DATE(2021,01,19)) ||
(ISBLANK(selectedParam)))
//note: the date filters are just an example, not how you would actually slice these.
return CALCULATE([Measure], dateFilter)
But you should look into Calculation Groups, as it is the nicest way to do what you're after. https://www.sqlbi.com/blog/marco/2020/07/15/creating-calculation-groups-in-power-bi-desktop/

Can we compare a row value with another row value in the table and highlight it in Power BI?

I have a table where 3 columns can have same value
Example:
Name Score_a Score_b Score_c
A 12 15 18
B 3 3 3
C 20 25 30
I want to highlight ( with a colour ) the row B since all the three scores are same.
I am unable to do it with conditional formatting available.
Can something be worked out using DAX? Please help!
Yes, first create a measure using the following dax formula:
Measure =
IF(
SELECTEDVALUE( 'Table'[Score_a] ) = SELECTEDVALUE( 'Table'[Score_b] ) &&
SELECTEDVALUE( 'Table'[Score_b] ) = SELECTEDVALUE( 'Table'[Score_c] ), 1, 0
)
Then you need to use conditional format on every column that you want to highlight and select the Measure you created.
This is the result

Power BI: Count numbers by Today, and the count numbers of the previous years at the same date

I'm new to Power BI and DAX.
I want to show the total ID count of this year and the total ID counts of previous years at the same dates each of which is associated with a different Category_Number.
The below tables show the original data set (1st table) and the result table (2nd table) I would like to have.
enter image description here
enter image description here
Any ideas or suggestions will be greatly appreciated.
Thanks!
You want to filter and use SAMEPERIODLASTYEAR.
To get the values of one category you can do:
Category_Nbr 80 = CALCULATE(COUNTROWS(myTable),myTable[Category_Nbr] = 80)
for the value of this but for the previous year you could use your DATE TABLE if you have it, if not, use the automatic one. I'll assume you don't have one so use the automatic.
Category_Nbr 80 LY = CALCULATE([Category_Nbr 80],SAMEPERIODLASTYEAR(myTable[Effective_Date].Date))
With this you can do a comparison over time
Category_Nbr Count YoY = DIVIDE([Category_Nbr 80 LY]-[Category_Nbr 80],[Category_Nbr 80 LY])
You can just adapt the filter for other categories.
Consider having a look into Quick Measures really nice way to start learning DAX.
Below are two measures I created.
The Total_ID measure works well. It shows the total number of IDs that have the Category_Number =80 and Effecitve_Date < Today.
The Total_ID_LY measure shows the total number IDs that have the Category_Number = 70, but doesn't show the Effective_Date< The same data last year.
I want the Total_ID_LY measure to have two filters, Category_Number = 70 (80-10) and Effective_Date < The same data last year of today.
Any helps?
Thanks!
Total_ID = COUNT('myTable'[ID])
Total_ID_LY =
VAR CurrentCategory = SELECTEDVALUE ( 'myTable'[Category_Number] )
VAR PreviousCategory =
CALCULATE (
MAX ( 'myTable'[Category_Number] ),
ALLSELECTED ( 'myTable' ),
KEEPFILTERS ( 'myTable'[Category_Number] < CurrentCategory )
)
VAR Result =
CALCULATE (
[Total_ID],
'myTable'[Category_Number] = PreviousCategory
)
RETURN
Result

Sum Current Month + 2 AND Next Month + 1 and Month After that

I have a metric I need to replicate in DAX for PowerBI and I am not quite sure how to do it.
The basics are this:
Fact Table: Opportunity
Dimensions: Created Date, Closed Date
The metric goes like this, I will just give an example, because I really dont know how to explain it.
SUM OF:
Created in FEB and Closed Date in FEB, MAR, APR
Created in MAR and Closed Date in MAR, APR
Created in APR and Closed in APR
This would happen for each month in the table/matrix.
Seems like I would need some variables something like
Measure =
VAR Month1 = SUM(ClosedOpps) where ClosedDate between CurrentMonth and CurrentMonth + 2
VAR Month2 = SUM(CLosedOpps) where ClosedDate betwwen CurrentMonth + 1 and CurrentMonth + 2
VAR Month3 = SUM(ClosedOpps) where ClosedDate = CurrentMonth + 2
Return Month1 + Month2 + Month3
My understanding is, the Closed Date filter would be the Table/Matrix Visual when I drag the column MonthYear into the visual
EDIT:
Here is a simplified replica of what they are doing in Excel
So The data on the left is the fact table. You can see when the Opps are created, when they are closed. I added in the Created MonthYear and the Closed MonthYear. The Pivot is what they have now in Excel. Dates across the top (Columns) are Created YearMonth, Dates for the Rows are Closed YearMonth.
I need to be able to SUM the numbers inside the of I3:K5 which total 5500 in the example.
UPDATE:
So I have added in a suggested Date Dimension table, Duplicated it (One for Open Date, one for Closed Date) I added a column DateDIM_KEY to each which is just a numerical index. The fact table has these keys, and they are loaded off of the same date range (2013 to 2030). The column ActualValue in the fact table is the column we would SUM.
Here is the updated Fact table sample. I pulled the DateDIM_KEY values directly from the date dimension for those dates.
You need a good date dimension. And you need to have it roleplaying for OpenDate and CloseDate. There are many good date dimensions out there. I like mine.
Assuming that you're putting 'OpenDate'[Month] on an axis label.
Opportunity Value = SUM ( 'Opportunity'[Value] )
MyMeasure iterator =
// start of the month on the current row of a pivot/axis label of a chart
VAR CurrentMonthStart = MIN ( 'OpenDate'[Date] )
// End of the month 2 months out
VAR ThreeMonthsOutEnd = EOMONTH ( CurrentMonthStart, 2 )
// This represents one row per month. You could also use a MonthAndYear type field.
// We will walk through the three open months we care about, and in each will sum
// the value for the opportunities opened in that month, with additional filters.
VAR NextThreeOpenMonths =
CALCULATETABLE (
VALUES ( 'OpenDate'[MonthIndex] ),
ALL ( 'OpenDate' ),
DATESBETWEEN ( 'OpenDate'[Date], CurrentMonthStart, ThreeMonthsOutEnd )
)
RETURN
// Iterate each OpenMonth
SUMX (
NextThreeOpenMonths,
// On each step of the iteration, grab the start of the currently iterated month
VAR IterMonthStart = CALCULATE ( MIN ( 'OpenDate'[Date] ) )
RETURN
CALCULATE (
[Opportunity Value],
// There is date context from visuals we want to ignore:
ALLEXCEPT ( 'OpenDate', 'OpenDate'[MonthIndex] ),
// filter CloseDate to be between the start of the currently iterated
// open month and the originally calculated ThreeMonthsOutEnd. The latter
// is static within the scope of the iteration.
DATESBETWEEN ( 'CloseDate'[Date], IterMonthStart, ThreeMonthsOutEnd )
)
)
Also, while writing the previous iterative approach, I realized we could do the work in a single setfilter:
MyMeasure set =
// MonthIndex is in my date dimension - super useful for arithmetic on dates.
// Read the readme.
VAR C = SELECTEDVALUE ( 'OpenDate'[MonthIndex] ) // want a short name below
// Table literal syntax - two column table, where each parenthesized expression
// forms a row. If it were much more, I'd do something clever with generate, but
// six cases are easy to write by hand.
VAR MonthFilters = {
(C, C),
(C, C+1),
(C, C+2),
(C+1, C+1),
(C+1, C+2),
(C+2, C+2)
}
RETURN
CALCULATE (
[Opportunity Value],
TREATAS ( MonthFilters, 'OpenDate'[MonthIndex], 'CloseDate'[MonthIndex] )
)
I like the latter a lot better, but didn't think of it until after writing the iterative version, so I'm leaving both. Set-based should be better performing.
Edit: some screengrabs I forgot:
Here's the relationship diagram for roleplaying date dim:
And here's the visual in action with both measures:
Best thing to do here is to add a custom column (under edit querys) with the date diff per month. Now you can filter after the column LeadTimeInMonth for you scenarios. If you drag and drop your fields into the visual you can filter by this column.
Date.Month([ClosedDAte])-Date.Month([OpenDate])
I am not sure what you really want to evaluate but if you need need exactly ClosedDate between CurrentMonth and CurrentMonth + 2 you can first evaluate the month from the ClosedDate then the month of today and filter after the result.

Creating an measure to compare week-over-week developments

My dataset includes information from at 26 different weeks. It lists all the open items from an accounts receivable database for each of the 26 weeks. Each of the report dates is exactly 7 days apart.
I am trying to compare the current receivables with the amount of the last week.
I thought that I will just extract the last report date with
LastReport:=LASTDATE(Report Date)
which gave me indeed the last report date. I go back 7 days with
PriorWeek:=DATEADD(LastReport;-7;DAYS).
This worked fine.
However, when I try to calculate the sum of last week using
CALCULATE(SUM(Total AR);Reportdate=PriorWeek)
I can an error that I cannot compare date and text fields.
I have checked the report date column is set to date.
What am I doing wrong?
I would say 'No need of ranking the Dates'. My solution is below using calculated columns:
Amount Variance =
VAR _PrevBlank =
ISBLANK ( [PrevWeek Amount] )
VAR _Amount = [Amount]
VAR _PrevAmount = [PrevWeek Amount]
VAR _Variance =
IF ( _PrevBlank, 0, _Amount - _PrevAmount )
RETURN
_Variance
I would suggest creating a date index using RANKX
RankDate = RANKX(Table1,Table1[Report Date],,ASC)
Then you can either create a calculated column that holds the previous week value
PreviousWeekCol = LOOKUPVALUE(Table1[Total AR],Table1[RankDate],Table1[RankDate]-1)
Or create a calculated measure that holds the prior week value
PreviousWeekMeasure =
VAR MaxDateIndex = MAX(Table1[RankDate])
RETURN CALCULATE(SUM(Table1[Total AR]),Table1[RankDate]=MaxDateIndex-1)