DAX - Filter before - powerbi

I need to count how many items/rows where created in the past months are.
general_report is the table name and [created] the date column format is in ormal dd/mm/yyyy hh:mm:ss as you can see here
For the goal, I have created this measure:
_created_last_month = COUNTROWS(FILTER(general_report, [Created] >= ( TODAY() - MONTH(TODAY() ) )))
I was also considering about creating a custom column which makes the same computation and then count how many items are valid in that column, with no success

Here are some examples (maybe you have to replace semicolon with comma)
Counts created in actual month:
_created_this_month:=
CALCULATE(COUNT(general_report[created]);DATESBETWEEN(general_report[Date];date(YEAR(TODAY());MONTH(TODAY());1);TODAY()))
Counts created in prev. month:
_created_last_month:=
CALCULATE(COUNT(general_report[created]);DATESBETWEEN(general_report[Date];date(YEAR(TODAY()-30);MONTH(TODAY()-30);1);EOMONTH(TODAY();-1)))
Counts created in the last "full" 6 months, the actual is not includet
_created_last_6_months_without_the_actual_month:=
CALCULATE(COUNT(general_report[created]);DATESINPERIOD(general_report[Date];EOMONTH(date(YEAR(TODAY()-30);MONTH(TODAY()-30);1);0);-6;MONTH))

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.

PowerBi DAX measure to sum duration of timespans filtered by current slicer

I need a DAX measure that gives me the sum of durations for multiple categories restricted by a date slicer.
In this simplified example there are 2 categories with 3 subcategories each. A DateTime Slicer on the dashboard is set to the timespan of 2nd of January 2021 noon to 6th of January midnight. I need the summed up duration of all categories in this timespan.
Input data:
A table containing multiple rows for each category with a start date and an end date.
The complicated part is that there are pauses between the timestamps.
Desired output:
A table on the dashboard containing the category and a calculated measure for the summed up duration during the sliced timespan.
When changing the slicer the meaure shall change as well.
My current solution for this problem is an M formulato create a list of all days in each timespan and to unpivot all lists. In the dashboard the count of rows gives you the number of days in the selected timespan. This solution though reqires a much larger input table and soes not work if you want to be exact on the second, only on days.
I tried so solve this via a measure but didn't make any progress worth showing here.
all datetime values are in the format dd.mm.yyyy hh:mm:ss (24h system)
I found a way to do it by using 2 measures.
First measure calculates the time during the timespan for each element:
I use one Date Table only consisting of all dates available which is the input for the slicer and the data Table called "Data".
duration_in_timespan_single =
VAR MinTs = MIN ('Date'[Date])
VAR MaxTs = MAX ('Date'[Date])
VAR MinUtcMin = MIN ('Data'[Date_Start])
VAR MaxUtcMax = MAX ('Data'[Date_End])
RETURN
IF(
AND(MinUtcMin >= MinTs, MinUtcMin <= MaxTs),
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinUtcMin),DOUBLE),
CONVERT((MaxTs-MinUtcMin),DOUBLE)),
IF(
MinUtcMin < MinTs,
IF(
MaxUtcMax > MinTs,
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinTs),DOUBLE),
CONVERT((MaxTs-MinTs),DOUBLE)
),
0
),
0
)
)
The second measure just sums up the first for each category:
duration_in_timespan = SUMX('Data',[duration_in_timespan_single])

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

Trying to figure out how ParallelPeriod works in DAX

I have a simple Power BI table that looks as follows:
I have two tables. A Date table and an Invoice table with a field representing invoice amounts. This is a 1-M relationship on Invoice.InvoiceDate.
The second column is simply a measure for the sum of invoices. The third and fourth columns are measures using ParallelPeriod to sum invoices for 12 months prior and 24 months prior. Even though these numbers are correct, I'm not entirely certain I know what's actually going on.
The measure for the 12-month parallel period looks like this:
Sum Invoice Amount 12 Months Ago =
CALCULATE (
SUM ( FactCustomerTransaction[InvoiceAmountDollars] ),
PARALLELPERIOD ( 'Date'[Date], -12, MONTH )
)
Here is what I think is happening. When the sum is calculated for say 2015-Feb, all values for that month are retrieved in the invoice (many side) table and summed to generate the "Sum Invoice Amount". The sames dates, minus 12 months, in the Date table, are retrieved and the same sum is generated for those range of dates for 'Sum Invoice Amount 12 Months Ago'. And then the same process for 24 months ago.
This works because of the 1-M relationship between Date and Invoice. Is this correct?
For 2015-Feb row, assuming the Year and Month Name column is on your 'Date' table, your filter context is 'Date'[Year and Month Name] = "2015-Feb". This filter corresponds to the dates 2015-02-01 through 2015-02-28 in your 'Date'[Date] column and that filtering propagates across the relationship to return only the rows in FactCustomerTransaction table where InvoiceDate is one of those dates and then sums the amounts corresponding to only those rows.
When you add PARALLELPERIOD, it works the same way except that after matching the dates 2015-02-01 through 2015-02-28 corresponding to 'Date'[Year and Month Name] = "2015-Feb", it shifts those dates back by 12 months and then propagates those shifted dates across the relationship.

Split single row of data in Power BI data source into multiple rows

I have a table in a Power BI data source with a column for term start and term end date (term length can be longer than a month), along with meta data on the term. I need to report on status of purchased terms as at the end of each month. As far as I can see, the best way of accomplishing this would be to create a calculated table with an entry for each month on which a term is active at its end.
For example, an entry in the original table with the following data:
TermStartDate TermEndDate PurchaseAmount
2018-01-03 2018-04-12 100
Would end up in the calculated table as follows:
MonthPurchased PurchaseAmount
2018-01 100
2018-02 100
2018-03 100
How to accomplish this? Is there a better way than creating a separate calculated table to get this data? Any help or advise is appreciated
I managed to solve this myself, I detail the required steps below for reference:
Change start and end date column data types from Datetime to Date. <- This is needed to ensure we only generate dates on day boundaries in the next step
Add custom column with the following formula:
Month = List.Select( List.Dates([TermStartDate], Number.From([TermEndDate] - [TermStartDate]) +1, #duration(1, 0, 0, 0)), each _ = Date.EndOfMonth(_) )
This generates a list of dates between start and end, then filters to only leave the dates that are at the end of a month
Expand to new rows on the new Month column (menu at the top of the column)
Use Detect Data Type option on the Month column to change the datatype from Any to Date (for some reason I cannot manually select Date, the DataType menu option is greyed out on the Month column)