Power BI cumulative count with multiple condition - powerbi

Did anyone know how to convert RunningCount into Power bi Dax ?
I test on RunningTotal, Rankx but seems not working.
The [year] is just a text column not in Datetime format.
I still new on this and not sure if my explain is good enough or not. Sorry for any inconvenient cause.
I try to create measure/ calculation column in power bi from the formula below.
I need the count by Year, break by column like product, customer, rate and category.

Before I get into my solution, there are a few assumptions I had to make:
The "Year" column is supposed to be years, and not five digit numbers. So in my data I dropped the second "2" in each (i.e. "20213" -> "2013").
You may have another column in your data to break ties, but given the data you provided, there is no way to rank the first and third lines (they both have product ABC and year 2003).
Given those assumptions, here is my solution...
First, here is what my data looks like. I added an ID column so that we can see every row, even duplicates.
From there, you can simply add a new column with the following formula.
Running Count =
COUNTROWS(
FILTER(
'Data',
[ProductName] = EARLIER([ProductName]) &&
[Customer] = EARLIER([Customer]) &&
[Seller] = EARLIER([Seller]) &&
[Year] <= EARLIER([Year])
)
)
The EARLIER function is being used to specify a ProductName, Customer, etc. from the row of the table to be used in the filtering of the data. Once we have the data filtered, we can simple count the number of rows.
The final result looks like this. As noted in my second assumption, there is no way to break ties, so my numbers are slightly off from what you have in your screenshot

Related

IF 'AND-OR' ISFILTERED combination in DAX giving problems

Below is the sample dataset
The data has two slicers ( date and category ) shown below
I am writing a DAX Statement to multiply the sum(values) * 10 only if the date range is in the current year 2023.
The StartYear gives the start of the current year, firstD gives the lowest date from the date slicer.
Formula =
var new = sum(Test[Value]) * 10
var startyear = DATE(YEAR(TODAY()),1,1)
var firstD = CALCULATE( MIN( Test[Date]), ALLSELECTED(Test[Date]) )
return if( ISFILTERED(Test[Categories]) && firstD >= startyear, new, 0 )
Now when I filter dates to 2023, the total value should be 2300 but it shows as 0
However the DAX works when I select A or B
If we remove the ISFILTERED function then, it gives wrong value, the expected value is 0 because the start date is in 2022, but it shows 650
let me know if that is the right syntax
It looks like you are not using a separate calendar table to handle this, which you need!
In your very last example you have set your slicer to some time late 2022, but the minimum value of 'Test'[Date] for your selected category is in year 2023. Hint: set the slicer to e.g. 2022-12-14, this will include a 2022-date for Category A in your data.
Your measure behaves exactly how it is supposed to, in other words!
To fix this, you need to do the following:
Create a calendar table in your model, this should contain contiguous dates, which is necessary for the filtering method you want
Establish a relationship between the calendar table and existing Test table.
Use the date column from your new calendar table in your slicer and as date reference in your measure
Exactly how to create a calendar table is thoroughly documented on Google, I recommend you search and find an article or video you understand for implementing this.
Lastly: Your use of ISFILTERED in this measure seems strange, since you mention nowhere the requirement of only showing a number if the column you are testing filtering on is filtered, if that makes sense.. :-) The way you describe your calculation, you only need to check whether the selected date range starts in current year.

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date

Filter by last not blank date in Power BI

I have data from multiple countries on a monthly basis. Since the updates are not regular, I want to set up filter to visuals, so they would show the last month for which I have data from all the countries. I have data from each country loaded into a separate dataset, which then are merged into one big. Is there an easy way to place such filter? I managed to use "LASTDATE" function in each of country sets to find which date is last, but if I try to filter with that measure, I simply get nothing in a result. Thanks!
Well, this feels a little clunky to me but I believe it will work for you. There are two steps. The first is to create a summary table that reads through your data and counts the number of distinct countries that you have in each month. This will be a new table in your model, so go into the modeling tab, click 'New Table' and add this DAX. Obviously, correct for your table and column names.
SUMMARIZED_ROWS = SUMMARIZE(
'Table1'
,Table1[Month]
,"CountOfCountries"
,DISTINCTCOUNT(Table1[Country])
)
Now add a measure to the table (or anywhere) like this:
MonthWithMostCountries = CALCULATE(
LASTNONBLANK(SUMMARIZED_ROWS[Month], 1 )
, FILTER(SUMMARIZED_ROWS, SUMMARIZED_ROWS[CountOfCountries] = MAX(SUMMARIZED_ROWS[CountOfCountries]) ) )
This is going to give you the month where you have the most distinct countries in your data. You'll want to look at it in a card or similarly isolated visual as it is a measure and can be affected by filter context.
So, on the left is my mock data - 3 countries, 3 months each with a 1 month stagger. On the right you see the result of the Summarize table. Then the measure showing the final result.
Hope it helps.

Measure in DAX to calculate YTD for chosen month only for Power BI

How to construct DAX measure to calculate sum of YTD value for specific month?
Here we have FactTable grouped by months. FactTable is filled with both Actual data and Forecast data. The only way to know when Actual end is information in table [Cut of date] in column [End of YTD]. In table [Cut of date] in column [End of YTD] – it is a single value table – we have the interesting chosen month, for which we want to see the calculation of YTD. In our case it is March. FactTable is updated irregularly every month with usually one month delay. There is no way of linking it to time functions like TODAY because of irregular update.
We would like to have a correct value of YTD displayed in yellow Card Visual for the month [End of YTD]. When we click on the slicer on "2018-03" we get almost what we want – correct value of 66 in the yellow Card. However this solution is not automatic. I want to see correct value automatically when the [End of YTD] month changes, in our case to April or then to May. I do not want it done by user.
My desperate effort can be downloaded from file: DAX YTD.pbix
I pursued the deer in various ways:
By using FILTER function in DAX measures. But it seems that the
FILTER function is to harsh. It is applied to fact table first,
selecting only one month, and then calculating YTD value wrongly. So if
there would be any option for forcing order of calculation and filtering, there would
be hope.
I tried SWITCH function to display proper result
for specific month and 0 or null for other months. Although I
succeed in this, I was not able to take advantage of it. When it
came to filtering I was as hopeless as before. BTW I would be able
to make it if SWITCH produced totals at the end of the table, but it
does not. Surprisingly.
I put some hopes in RELATED function to display proper results in the [Cut off date] table. I have not walk out of the fog so far.
I would appreciate your help.
Update before bounty.
Going to higher level. I have introduced a Category column to FactTable. Please download DAX YTD by category.pbix. So filtering gets more complex now. I would like to have correct YTD figures for Apples category.
Did you use the Date column from the Calendar table, instead of the one from FactTable?
If you use the date column from FactTable, when you apply a filter on the date, it will filter on the fact records which is in March, and then do the calculation afterwards, hence the result 33.
If you use the one from Calendar, when you apply a filter on it, it filters the records on Calendar (which you want to show in the chart), so the underlying calculation will still remain intact.
A working example:
Calendar = CALENDAR(DATE(2010, 1, 1), DATE(2020, 12, 31))
I suggest you to change the calculations of the measures to avoid missing values in some cases:
Total = SUM(FactTable[Value])
MTD = TOTALMTD([Total], 'Calendar'[Date])
YTD = TOTALYTD([Total], 'Calendar'[Date])
UPDATE:
It's much clearer to me what you want to achieve now but it still seems an XY problem to me.
I understand that you want to show the dashboard as is so that users do not need to click/input every time to see what they are supposed to see. That's why I don't get why you need to create a new table to store the Cut off date (End of YTD). How is it going to be maintained automatically?
The relative date filtering solution above actually still works in the .pbix file you've shared. If you drag the Date column from the Calendar table to visual level filters for the yellow card and add the relative date filtering, it should work as below:
For the End of YTD visual, you can use the following measure to get the first day of last calendar month, so you don't need to create another table for it:
End of YTD = EOMONTH(TODAY(), -2) + 1
And hopefully this is what you want to achieve:
Updated file for your reference.
UPDATE again:
I think you'll have to write your own YTD calculation instead of using the built-in one, so that you can make use of the cut off date you defined in another table. Here I assume that you have one and only one row in 'Cut off date'[End of YTD]. Note that I've added ALL() to the filter, so that the yellow card remains the same (66) instead of showing blank when some other rows/filters are clicked:
YTD_Special =
CALCULATE(
[Total],
FILTER(
ALL(FactTable),
FactTable[Date] >= DATE(YEAR(VALUES('Cut off date'[End of YTD])), 1, 1) &&
FactTable[Date] <= VALUES('Cut off date'[End of YTD])
)
)
I would resolve this by adding a calculated column to your Calendar table to categorise each row into either "YTD" or "Other", e.g.
Is YTD =
IF (
[Date] >= DATE ( YEAR ( DISTINCT ( 'Cut off date'[End of YTD] ) ), 1, 1 )
&& [Date] <= DISTINCT ( 'Cut off date'[End of YTD] ),
"YTD",
"Other"
)
I would then add the new Is YTD field to the Visual level filters of your Card visual, and choose YTD from the Basic filtering list. The measure shown can be your simple Total measure: SUM(FactTable[Value]).
This is a far more flexible and resuable solution than any specific measure gymnastics. You will not need an explosion of measures to apply the required logic on top of every base measure - they will all just work naturally. You can apply the filter at any level: Visual, Page, Report, or put it in a Slicer for control by the end user.
I prefer to return text results e.g. "YTD" / "Other" (rather than 1/0, True/False or Yes/No), as this allows for easy extension to other requirements e.g. "Prior YTD" (1 Jan 2017 to 1 Mar 2017). It also is clearer when used in visuals.
Actually I shouldn't claim the credit for this design - this roughly follows how Cognos Transformer's Relative Time functionality worked back in the 90s.
I did something like this in my Periodic/YTD report (last sheet): http://ciprianbusila.ro/
I have used the index value of the month selected (range 1-12) and based on this I have created a measure using max function please see the code below:
ACT = var
ACT_periodic=calculate([Value],Scenarios[Scenario]=values(Scenarios[Scenario]))
var max_month=max(Periods[Period Order])
var ACT_YTD=CALCULATE([Value],Scenarios[Scenario]=VALUES(Scenarios[Scenario]),all(Periods[Month]),Periods[Period Order]<=max_month)
var myselection=if(HASONEVALUE(MRD_view[.]),values(MRD_view[.]),"PERIODIC")
return
switch(
true(),
myselection="PERIODIC",ACT_periodic,
myselection="YEAR TO DATE",ACT_YTD,
ACT_periodic
)

Aggregate the last value for child categories with DAX

I need to sum the values of stock on hand at a selected date, these values need to roll up into 2 or more categories.
The following measure gives me the on hand value at the lowest level item, but when it rolls up to the sub Category or Category level, it sums all the values and not the LASTNONBLANK per child item.
On Hand = CALCULATE(SUMX(Stock,[SOH]),FILTER('Calendar',[Date] <= LASTNONBLANK('Calendar'[Date],SUM(Stock[SOH]))))
My data set is similar to this:
Now to get the last SOH value where date <= 10 Dec 2017 works with my measure, with results like this.
As soon as I need to roll the aggregation up by removing the Size column the sum does not work as expected anymore.
This is what I need it to look like:
Similar to that I need the Category level to sum all the LASTNONBLANK values of the lowest level items, like this:
Any help would be appreciated.
I normally prefer to use measures rather than calculated columns in DAX but, because the relevant SOH values rely on a comparison the lowest level, this is a situation where I would add a calculated column.
Latest SOH:=
if(
CALCULATE(
LASTDATE('Stock'[Date]),
ALLEXCEPT('Stock',Stock[Category],Stock[Sub Category],Stock[Size])
)=Stock[Date],
'Stock'[SOH],
BLANK()
)
Starting from the middle and working out:-
ALLEXCEPT(...) is looking at all entries in the table that have the same value for Category, Sub Category and Size
CALCULATE(...) is then finding each of the last dates where there is a match
='Stock'[Date] is then checking to see if this row is the row with the highest date it can find with this Category/Subcategory/Size combination
If the values do match, then bring through the value of SOH, otherwise leave the cell blank.
Here's what it looks like in PowerPivot:
I wasn't quite sure what you wanted your dates to show. I've just added a measure that takes the LASTDATE of the date column:
And
I hope this helps!
Try to group by columns Category and Subcategory using sumx inside
GROUPBY (
Category,
SubCategory,
“SOH”, SUMX(expression)