I have a table in my power BI with the following fields :
Preview of the data:
The column "platform" has 3 possible values : application, shop, website
"day" is of type Date
"hour" is of type "Date/Time" (same information as "day" + has the hour)
I added a measure to calculate the conversion_rate (orders/visits):
conversion_rate = DIVIDE(SUM(Table[orders]), SUM(Table[visits]))
Then I calculated for every day the conversion_rate from 7 days ago (to be able to compare them):
conversion_rate_7_j = CALCULATE(Table[conversion_rate],
DATEADD(Table[day],-7,DAY)
)
Now my data looks like this:
What I want to do is calculate the conversion rate from 7 days ago but for the same hour.
However I couldn't find a function that substracts field of type Date/Time while taking in consideration the hour.
A solution I thought of is to calculate orders and visits -7 days same hour separately and then divide them to have the conversion rate -7 days same hour:
orders_7_j_hourly =
VAR h = Table[hour] - 7
VAR p = Table[platform]
Return CALCULATE(
MAX(Table[orders]),
Table,
Table[hour] = h,
Table[platform] = p
)
Since my data is grouped by hour (Date/Time) and platform,
And since sometimes for a certain hour I have values for the platform = "application" but not "shop",
My function did not work especially that I am using MAX, this associated the number of orders to the wrong platform.
Can you please help ?
Sample data : https://ufile.io/y1blqgqn
Datetime values are stored in units of days. Thus you can simply shift hour by 7 in your measure.
conversion_rate prev_week =
VAR CurrHour = SELECTEDVALUE ( Table1[hour] )
RETURN
CALCULATE (
[conversion_rate],
ALL ( Table1[day] ),
Table1[hour] = CurrHour - 7
)
Sample results:
Did you try to use HOUR function ??
conversion_rate_7_hour = CALCULATE( [conversion_rate],
FILTER( ALL(Table),
SELECTEDVALUE(Table[day]) - 7 = Table[day]
&& HOUR(SELECTEDVALUE(Table[hour]) - 7) = HOUR( Table[hour])
))
When we put Table[hour] to visualization it should work.
Ps. best pratice => if your refer to measures in your calculations,do not include the table prefix
You can create an additional column called hour in your dataset
Once you have that, you bring the hours in the viz, the following measure can give you what you want
convRate-7 = CALCULATE([convRate],DATEADD('Table'[day],-7,DAY))
Related
Using Power Bi desktop,
I need to create a query where the result will be the current month's working days.
For example July 2021 has 22 working days and so on.
My goal for achieving this will be to be to average the number of lines processed divided into the number of working days for the current month.
Will this be possible?
You can always get the job done only by creating just a single measure and nothing else like following
_count =
COUNTX (
FILTER (
VALUES('fact'[_factDate]),
WEEKDAY ( 'fact'[_factDate], 1 ) <> 1
&& WEEKDAY ( 'fact'[_factDate], 1 ) <> 7
),
'fact'[_factDate]
)
The minimum dependency of the calculations are having a calendar table like this
Calendar_Date
Calendar_Year
Calendar_Month
1/1/2000
2000
1
first create a calculated column in you calendar table (Dates for my case) with this below code-
Column = if(
FORMAT(Dates[date],"dddd") = "Saturday"
|| FORMAT(Dates[date],"dddd") = "Sunday",
0,
1
)
now create a measure as below-
weekday = sum(Dates[Column])
now, create visual with month and new measure.
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
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.
I have the following Data :
I want to achieve a solution where, when I filter year, it returns me the average of Goodwill of that year and the previous year.
So for my year filter 2017: Average of Goodwill in 2017,2016
year filter 2016: Average of Goodwill in 2016,2015
.... and so on
The year is in General format (NOT Date format) ..
Expected OUTPUT Values:
Not sure what you have tried (or how familiar you are with Power BI/DAX), but you will most likely need to use a combination of DIVIDE, CALCULATE, and ALL. The DIVIDE function isn't super necessary, but it is a great habit to get into as it catches errors. Combining the CALCULATE and ALL will allow you to take the sum for the selected year and the prior year.
What I would do is this:
Goodwill - 2yr Avg =
VAR MaxSelectedYear = MAX([Year])
VAR PriorYear = MaxSelectedYear - 1
VAR MinYearInData = MINX(ALL(Data), [Year])
RETURN
DIVIDE(
CALCULATE(SUM([Goodwill]), FILTER(ALL(Data[Year]), [Year] = MaxSelectedYear))
+
CALCULATE(SUM([Goodwill]), FILTER(ALL(Data[Year]), [Year] = PriorYear))
,
IF(PriorYear < MinYearInData, 1, 2),
BLANK()
)
The IF statement at the end will catch when you are looking at the first year, so that the sum is only divided by 1 instead of 2. The sum will only be 1 year of data since when you filter the Data table to the prior year, there will be no data.
Maybe something like this?
My Average =
IF(HASONEVALUE(Data[Year]);
DIVIDE(
CALCULATE(SUM(Data[Goodwill]);FILTER(ALL(Data[Year]);Data[Year]>=SELECTEDVALUE(Data[Year])-1 && Data[Year]<=SELECTEDVALUE(Data[Year])))
;2);
BLANK()
)
HASONEVALUE, just to identify if my current scope only has 1 year selected for the calculation to be applied.
Than getting the value for the current year and previous year with FILTER and SELECTEDVALUE
I am hardcoding the division by two, but you can adjust it depending on your dataset and purpose.
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)