DAX Last Year to Date - powerbi

So I know this question has been asked a few times, and I've religiously looked over different approaches, however I still don't quite understand why I'm getting an incorrect result.
Case: I have Sales Data from ~2016 -> 2019 (up until the 2/18/2019) I'm have a Measure to show me the YTD, however I'm looking for a measure for Last Years to date(the 18th in this particular circumstance).
Right now, I have this:
Total Sales LYTD =
CALCULATE (
[Total Sales],
SAMEPERIODLASTYEAR (
FILTER (
VALUES ( Sales[Completed Date] ),
Sales[Completed Date] <= MAX ( Sales[Completed Date] )
)
)
)
The logic to me makes sense, but I'm sure I'm missing something, has it appears it's grabbing the ENTIRE total of 2018 when in reality i'm looking for 01/01/2018 -> 2/18/2018
This is going to be dynamically uploaded with new sales data
What am I missing? Thank you so much!

Not sure I understand your table setup so lets look at this scenario and hopefully it helps.
Suppose you have the data in two tables, Sales and Calendar, and there's a 1:* relationship between the calendar and the sales tables. Then I would write the measures like this:
SalesToDateThisYear =
calculate(
Sum(Sales[Sales]);
Calendar[Year] = Year(Today())
)
and
SalesToDateLastYear =
var dateLastYear = Today() - 365
return
calculate(
Sum(Sales[Sales]);
Calendar[Year] = Year(dateLatsYear);
Calendar[Date] < dateLastYear
)
The two filter arguments are combined with a logic AND. So only dates from the first of last year to today's date last year will be included.
If you want to use the SamePeriod-function you can probably write something like this
SPLY =
calculate =
Sum(Sales[Sales]);
SamePeriodLastYear(
Filter(
Values(Calendar[Date]);
Calendar[Date] >= Date(year(today()); 1; 1) && Calendar[Date] < Today()
)
)
)
The SamePeriod-function takes a set of dates (this year) and converts them to dates last year.
Cheers

Related

Moving Annual Total with DAX Power BI

I'm trying to calculate MAT (Moving Annual Total) using DAX, but can't realize exactly what I want.
I have the data as below.
What I'm trying to is calculate the total of treatment for each 12 month, like "Jan 21 - Dec 21" which has 'date' from 2020/1/1 to 2020/12/1. i.e. 'A' appears 4 times in that period, so the result will be like below.
Then I'd like to continue this for each latest 12 months, and finally visualize it like below.
I've read that I should use CALCULATE and DATESPERIOD in DAX, can't calculate exactly though. The following code is the one I tried and failed.
Moving Annual Total = CALCULATE(
COUNTA('2017-2022Q1'[idnum]),
DATESINPERIOD('2017-2022Q1'[mat].[Date], LASTDATE('2017-2022Q1'[mat].[Date]), 12, MONTH))
Could someone kindly give me an advise to realize this?
Thanks.
*This is the sample file.
https://drive.google.com/file/d/1gDNeBe5KiKBqx3cZ7G0SMiSQ23w96NF4/view?usp=sharing
In your dax measure, I recommend you first to create a date table and create a one-to-many relationship with the fact table(your table: '2017-2022Q1') ; then filter the date table in your calculate measure, not the fact table('2017-2022Q1') directly as you did here. You should follow the best practice.
For Example: How to create a date table using dax:
Date =
VAR MinYear = YEAR ( MIN ( '2017-2022Q1'[date] ) )
VAR MaxYear = YEAR ( MAX ( '2017-2022Q1'[date] ) )
RETURN
ADDCOLUMNS (
FILTER (
CALENDARAUTO( ),
AND ( YEAR ( [Date] ) >= MinYear, YEAR ( [Date] ) <= MaxYear )
),
"Calendar Year", "CY " & YEAR ( [Date] ),
"Month Name", FORMAT ( [Date], "mmmm" ),
"Month Number", MONTH ( [Date] )
)
Your final code could be like this:
Moving Annual Total = CALCULATE(
COUNTA('2017-2022Q1'[idnum]),
DATESINPERIOD('Date'[Date], LASTDATE('Date'[Date]), -12, MONTH)
)
if you define the start date using the lastdate() function, then It returns the last date in your filter context. you should also specify the interval as (-12) month to extract all dates within 1 year period.
Hope It helps.

Calculating Monthly Average over time with only Start and End Dates in Power BI

In order to track our average headcounts and turnover trends, I had created a report in Power BI that essentially expanded a table with employee start/end information to give a record for each associate every day they were employed at the company.
While this solution works, I end up with a table containing millions of rows which does not seem very efficient.
I have looked into other possible solutions in DAX, but have not found anything that will give me the exact same output. It seems like most solutions rely on taking the timing from the start date and end date of a month and then averaging them, which is not quite what I am trying to do.
I have attached a simplified pbix file that shows the desired output of what I am trying to get at. Any advice would be appreciated.
pbix example
Final code ended up looking like this:
All Employees = countrows ('Employees')
Terminations =
Calculate(
Countrows('Employees'),
USERELATIONSHIP('Employees'[End Date],'Calendar'[Date])
)
Active Employees =
AVERAGEX(
VALUES('Calendar'[Date]),
VAR CurrentDate = 'Calendar'[Date]
VAR HiredBeforeCurrentDate =
Filter(
ALL('Employees'[Start Date]),
'Employees'[Start Date] <= CurrentDate
)
VAR HiredAfterCurrentDate =
FILTER(
ALL('Employees'[End Date]),
OR('Employees'[End Date] >= CurrentDate, isblank('Employees'[End Date])
)
)
RETURN
CALCULATE(
Countrows('Employees'),
HiredBeforeCurrentDate,
HiredAfterCurrentDate,
ALL('Calendar')
))

Power BI: Use unrelated date table to create a measure

Hi I have been struggling with this for a bit now and I hope I didn't miss a previous question. I am trying to get a count of the vehicles we have based on an EOMONTH date. We are buying and selling cars on a regular basis and for reporting we need to know how many we had at the end of each month and the report is a rolling 12 months.
I've tried creating the relationship with the purchasedate of the vehicle to the date of my date table but when I create the measure (Used to calculate the number of vehicles purchased but haven't been sold):
SalesBlank = CALCULATE(
COUNT(Vehicles[MVANumber]),
FILTER(Vehicles, Vehicles[purchasedate] <= RELATED('Date'[EOMONTH]) && ISBLANK(Vehicles[saledate])))
I only get a count of vehicles purchased that month and don't have a sale date - I'm not surprised because my relationship with the date table is the purchase date.
How can I set up a measure to look at the date table and filter the vehicles table with this logic:
purchasedate <= date[EOMONTH] && ISBLANK(salesdate)
Any help would be greatly appreciated!!
Thanks,
Matt
Sample Data and Desired Results
Relationships
If I understand you correctly, you want to get a count of the vehicles on hand at the end of each month. That could be calculated by counting the vehicles with a purchase date less than or equal to the selected end of month and subtracting the count of vehicles with a sale date less than or equal to the selected end of month.
You can create an active relationship between Vehicle[PurchaseDate] and Date[Date]. Then create an inactive relationship based upon Vehicles[SaleDate] and Date[Date].
You could use a measure that is something like this:
Inventory Count =
VAR MaxDate =
MAX ( 'Date'[Date] )
VAR MinDate =
CALCULATE ( MIN ( 'Date'[Date] ), ALL ( 'Date' ) )
VAR Purch =
CALCULATE (
COUNT ( 'Vehicles'[VehicleID] ),
DATESBETWEEN ( 'Date'[Date], MinDate, MaxDate )
)
VAR Sales =
CALCULATE (
COUNT ( 'Vehicles'[VehicleID] ),
USERELATIONSHIP ( 'Date'[Date], Vehicles[Sale Date] ),
DATESBETWEEN ( 'Date'[Date], MinDate, MaxDate )
)
VAR MaxPurDt =
CALCULATE ( MAX ( 'Vehicles'[Purchase Date] ), ALL ( 'Vehicles' ) )
VAR MaxSlDt =
CALCULATE ( MAX ( 'Vehicles'[Sale Date] ), ALL ( 'Vehicles' ) )
RETURN
IF (
MIN ( 'Date'[Date] ) <= MaxPurDt
|| MIN ( 'Date'[Date] ) <= MaxSlDt,
Purch - Sales
)
This measure gets a cumulative count of purchases and a cumulative count of sales and then subtracts them. The IF check is to avoid propagation of cumulative totals beyond the maximum date in the Vehicle table.
I'm not sure how to interpret your showing of just 3 months in the desired results. This will produce the same answers as what you have, but without a filter applied to the table, it starts at 3/31/2016 (the date of the first sale).
Edit: There's probably a more efficient way along the lines you were thinking, but it is escaping me at the moment.

How to find day over day change in summarize table taking two columns into account

I have a summarize table that is summed by the Date and Building_Name. I am trying to figure out how to add an increase/ decrease column like my table below. I want to show if the 'total unsigned' has increased from day to day for each building.
I cannot get a formula that will take the previous days total for one building - current days # of total unsigned. Trying to get the forth column for my report. 
I can get it to work if I am just showing day over day change if I am not also trying to add the Building_name to the table.
Unsigned Prev Day =
VAR CurrentDay = SELECTEDVALUE(SummarizeTable[Day Number])
VAR CurrentMonth = SELECTEDVALUE(SummarizeTable[Month Number])
VAR MaxDayNumber = CALCULATE(MAXA(SummarizeTable[Day Number]))
Return SUMX(
FILTER(ALL(SummarizeTable),
IF( CurrentDay = 1,
SummarizeTable[Day Number] = MaxDayNumber && SummarizeTable[Month Number]= CurrentMonth-1,
SummarizeTable[Day Number] = CurrentDay -1)),
[Total Unsigned])
Edit:
Thank you for the help, you definitely put me on the right track. This is the formula I ended up using. Thank you again for the help!
Unsigned Prev Day =
VAR MostRecentDate = MAX ( 'SummarizeTable'[Date] )
RETURN
CALCULATE (
[Total Unsigned],
ALL ( 'SummarizeTable'[Date], 'SummarizeTable'[Day Number], 'SummarizeTable'[Month Number] ),
'SummarizeTable'[Date] = MostRecentDate - 1
)
This assumes that you have or can make a column, 'SummarizeTable'[Date]. If you already have month and day, this should be trivial. This solution takes advantage of the fact that DAX has well-behaved arithmetic on dates.
Additionally, you should look at building a date dimension, rather than doing all of this out of a single table. It will ultimately make your life a lot easier. There are a bunch of good date dimensions out there, but I'm partial to mine.
EDIT: Per discussion in comments the goal is to add this as a calculated column to a data table. The definition above is intended to be used as a measure.
# Increase/ Decrease =
CurrentRowDate = 'SummarizeTable'[Date]
RETURN
CALCULATE (
SUM ( 'SummarizeTable'[Total Unsigned] ),
ALLEXCEPT ( 'SummarizeTable'[Building] ),
'SummarizeTable'[Date] = CurrentRowDate - 1
)
This will add a column to 'SummarizeTable' that has the sum of [Total Unsigned] for the same value of [Building] as is on the current row and with a date 1 less than that on the current row.

How do I get working days between dates in Power BI?

Currently, I have calculated the working days between two date by using the following formula.
TAT = CALCULATE(SUM('Days Table'[Is Work Day]),
DATESBETWEEN('Days Table'[Date],'Re-run Data'[DATE_ORDERED],'Re-run
Data'[DATE_COMPLETED]))
The problem is that if a client level has multiple orders that span all the working days in the Days Table, their sum includes all of the days instead of the sum of days between orders. This also skews the averages.
Does anyone have simpler solution to get number of working days between two dates?
Your current solution relies on having the [Is Work Day] column in your calendar table.
This measure returns the number of working days between the Date Ordered and Date Completed - based on working days being Monday - Friday, and excluding dates listed in a 'Holidays' table, without needing any calculated columns:
TAT =
COUNTROWS (
FILTER (
ADDCOLUMNS(
DATESBETWEEN (
'Calendar'[Date],
MIN ( 'Re-run Data'[DATE_ORDERED] ),
MAX ( 'Re-run Data'[DATE_COMPLETED] )
),
"Is Weekday", WEEKDAY ( 'Calendar'[Date], 2) < 6,
"Is Holiday", CONTAINS ( Holidays, Holidays[Holiday Dates], 'Calendar'[Date] )
),
[Is Weekday] = TRUE() && [Is Holiday] = FALSE()
)
)
See https://pwrbi.com/so_54718437/ for worked example (PBIX)
Upon further analysis, the formula I included in my question does exactly what I need it to do.