I have a data with columns Profit and Date and I have created 2 new measure.
Measure1 = SUM(DF[Profit])
Measure2 = AVERAGE(DF[Profit])
I have to create another measure such that it is based on condition i.e.
Measure3 = DF[Profit]/Measure1(If Date = 2022-06-01)
DF[Profit]/Measure2(Else)
I want to create a new measure and not a column? Is it possible?
I am under the assumption that it is not possible because in measure3 the numerator is not aggregated.
Yes, when doing DAX you always has to switch between tables, columns and so-called scalar value. In your case, you have to convert the Date = 2022-06-01 using a scalar function.
Most simple way to do it is use an aggregation function to get the value. Like MAX
Same goes for Df[Profit], you have to aggregate it.
Measure3 =
VAR tmpDate =
MAXX(
Table,
Table[Date]
)
RETURN
IF(
tmpDate = DATE(2022, 06, 01),
DIVIDE(
SUM(Df[Profit]),
Measure1
),
DIVIDE(
SUM(Df[Profit],
Measure2
)
)
Note, maybe I would improve the the tmpDate as an IF statement that checks that in the current context the date has only one value. Something like:
tmpDate =
IF(
HASONEVALUE(Table[Date]),
MAXX(
Table,
Table[Date]
),
BLANK()
)
Related
I'm freshly new to DAX & PowerBI, I tried to create a measure column that will count the number of child of each parent has.
The table is something like this (please understand this table structure might be not ideal, but I can't change the existing).
What I expect is to create a new column that will count how many "child" that the "parent" has based on "Parent ID". Like this.
I've tried using this formula but it returns error
Childcount =
COUNTROWS(
FILTER(
Table,
FILTER(
Table,
Table[Parent ID] <> BLANK()
) = Table[ID]
)
Thank you for your help.
This can be done. Just a quick note, there are two types of calculations you canmake in Power BI: measure and calculated column. I Guess you're in nedd of a calculated column so here's a solution using calculated columns.
First create a calculated column like this:
Parent ID =
var idcol = [id]
var result =
IF(
[Type] = "Child",
CALCULATE(
MAX('Data'[ID]),
FILTER(
ALL('Data'),
'Data'[Type] = "Parent" && 'Data'[ID] < idcol
)
),
BLANK()
)
return
result
Then you can create a second calculated column like this:
Childcount =
var idcol = [ID]
return
CALCULATE(
COUNT(Data[Parent ID]),
FILTER(
ALL(Data),
'Data'[Parent ID] = idcol
)
)+0
Since you're new to Power BI/Dax I would highly recomend you check youtube and sqlbi for free introductory videos. Before you understand the concept of how calculations are performed in Power BI you're gonna have a tough time. But it's worth the time investment!
I have created NBRevenue Measure to get SUM of Revenue with two conditions as filter as per below screen shot, The issue is when i add [CurrentYear] then the data displayed in below screenshot(1) is wrong but when I hard code 2020 in screenshot(2) then data is correct.
I did check that the [CurrentYear] is whole number and the table 'AST DMNewLostMeasures'[Year] is too whole number.
Wrong Result- ScreenShot(1)
Correct Result - Screenshot(2)
I need to make this dynamic and hence please let me know what wrong I am doing or any other approach/suggestion would be great.
CurrentYear Formula
I think you should use a Year slicer rather than using a Measure reference inside your formula. That will make everything dynamic and result will be populated as per selected Year in the slicer. Your Revenue code should be as below-
NBRevenue =
CALCULATE(
SUM('AST DMNewLostMeasures'[Revenue]),
FILTER(
'AST DMNewLostMeasures',
'AST DMNewLostMeasures'[MeasureType] = "NewRevenue/Policies"
)
)
You can also change your CurrentYear measure as below-
CurrentYear =
CALCULATE(
MAX('AST DMNewLostMeasures'[Year]),
FILTER(
ALL('AST DMNewLostMeasures'),
'AST DMNewLostMeasures'[MeasureType] = "NewRevenue/Policies"
)
)
Assuming your CurrentYear measure returns what you expect, I'd recommend setting it as a variable rather than recalculating it for every row in your filter table:
NBRevenue =
VAR CurrYear = [CurrentYear]
RETURN
CALCULATE(
SUM('AST DMNewLostMeasures'[Revenue]),
FILTER(
'AST DMNewLostMeasures',
'AST DMNewLostMeasures'[MeasureType] = "NewRevenue/Policies"
&& 'AST DMNewLostMeasures'[Year] = CurrYear
)
)
I'm hoping someone can help as I've completely run out of ideas.
I'm working on performance reporting data, producing a number of visuals to summarise the most recent data. To allow users to retrospectively produce reports from previous quarters, I have added a date slicer as a way to "View data as at xxxx date".
Here's a rough representation of my data table - the due dates are in English format (dd/mm/yyyy):
The ratings are calculated in another system (based on a set of targets), so there are no calculated columns here. In reality, there are a lot more measures that report on different time periods (some weekly, some annually, etc) and there are different lags before the data is "due".
I eventually managed to get a measure that returned the latest actual:
MostRecentActual =
VAR SlicerDate = MAX ( Dates[Day] )
RETURN
CALCULATE (
SUM ( Data[Actual] ),
Data[Data due] <= SlicerDate,
LASTDATE ( Data[Data due] )
)
I'm not completely sure I've done it right but it seems to work. I'd be happier if I understood it properly, so explanations or alternatives would be welcomed.
What I'm trying to do now is a basic summary pie chart at the beginning which shows the proportion of the measures that were red, amber, green or unrated as at the date selected. So I would need it to count the number of each rating, but only one for each measure and only for the date that is closest to (but before) the slicer date, which would vary depending on the measure. So using the above three measures, if the slicer was set to 10/10/2019 (English format - dd/mm/yyyy), it would count the RAGs for Q3 2019/20 for measures A an C and for Q2 2019/20 for measure B as there is a time lag which means the data isn't ready until the end of the month. Results:- A: Amber, B: Green, C:Red.
If I were able to create the measure that counted these RAGs, I would then want to add it to a pie chart, with a legend that is "Rating", so it would split the chart up appropriately. I currently can't seem to be able to do that without it counting all dates before the slicer (not just the most recent) or somehow missing ratings from the total for reasons I don't understand.
Any help would be very gratefully received.
Many thanks
Ben
Further update. I've been working on this for a while!
I have created a COUNTAX measure to try to do what I was wanting to do. In some circumstances, it works, but not all and not in the crucial ones. My measure is:
TestCountaxpt2 =
VAR SlicerDate = MAX ( Dates[Date] )
VAR MinDiff =
MINX (
FILTER (
ALL ( Data ),
Data[Ref] IN VALUES ( Data[Ref] ) &&
Data[Data due] <= SlicerDate
),
ABS ( SlicerDate - Data[Data due] )
)
VAR thisdate =
MINX (
FILTER (
ALL ( Data ),
Data[Ref] IN VALUES ( Data[Ref] ) &&
ABS ( SlicerDate - Data[Data due] ) = MinDiff
),
Data[Data due]
)
RETURN
COUNTAX (
FILTER ( Data, Data[Data due] = thisdate && Data[Ref] IN VALUES ( Data[Ref] ) ),
Data[RAG]
)
It produces the following table for a subset of the performance measures, which looks almost ok:
Table showing the result of the TestCountaxpt2 measure:
The third column is the measure above and it seems to be counting one RAG per measure and the dates look correct as the slicer is set to 3rd January 2020. The total for column 3 confuses me. I don't know what that is counting and I don't understand why it doesn't add up to 7.
If I add in the RAG column from the data table, it goes a bit more wrong:
Same table but with RAG Rating added:
The pie chart that is produced is also wrong. It should show 2 Green, 2 Red, 2 Grey (no rating) and 1 Amber. This is what happens.......
Pie chart for the DAX measure, with RAG Rating in the legend:
I can see what it is doing, which is to work out the most recent due date to the slicer in the whole table and using that (which is 1st Jan 2020) whereas I want it to calculate this separately for each measure.
Link to PBIX:
https://drive.google.com/file/d/1RTokOjAUADGHNXvZcnCCSS3Dskgc_4Cc/view?usp=sharing
Reworking the formula to count the ratings:
RAGCount =
VAR SlicerDate =
MAX ( Dates[Day] )
RETURN
COUNTAX (
ADDCOLUMNS (
SUMMARIZE (
FILTER ( Data, Data[Data due] <= SlicerDate ),
Data[Ref],
"LastDateDue", LASTDATE ( Data[Data due] )
),
"CountRAG", CALCULATE (
COUNTA ( Data[RAG] ),
Data[Data due] = EARLIER ( [LastDateDue] )
)
),
[CountRAG]
)
Here's the table it produces:
The reason for Total = 4 for the third column is straightforward. The SelectDate is maximal over all of the Refs in the table and there are only four Refs that match that date.
To fix this and get the totals you're after, you'll need to iterate over each Ref and calculate the SlicerDate for each independently and only then do your lookups or sums.
I haven't tested this code but it should give you an idea of a direction to try:
MostRecentActual =
VAR SlicerDate = MAX ( Dates[Day] )
RETURN
SUMX (
ADDCOLUMNS (
SUMMARIZE (
FILTER ( Data, Data[Data due] <= SlicerDate ),
Data[Ref],
"LastDateDue", LASTDATE ( Data[Data due] )
),
"SumActual", CALCULATE (
SUM ( Data[Actual] ),
Data[Data due] = EARLIER ( [LastDateDue] )
)
),
[SumActual]
)
Going inside to outside,
FILTER the table to ignore any dates beyond the SlicerDate.
Calculate the LastDateDue for each Ref using SUMMARIZE.
Sum the Actual column for each Ref value using its specific LastDateDue.
Iterate over this summary table to add up SumActual across all Refs in the current scope.
Note that for 4, only the Total row in your visual will contain multiple Refs since the innermost Data table inside FILTER is not the entire Data table but only the piece visible in the local filter context.
In this measure - I'm creating a temp table to group by customer ID and return the year of the min order_date for each customer. I then want to count the # of customers that show up for a given year (basically just a row count).
What I'm struggling to understand is - this formula doesn't seem to look at the SUMMARIZE table within it. If I put year and this measure in a matrix, it counts based on the raw table, not the grouped version built by SUMMARIZE in the formula. Any ideas why it's evaluating this way?
COUNTROWS(
SUMMARIZE(
Orders,
Orders[Customer ID],
"min_order_date_year",
MIN(Orders[Order Date].[Year])))
The formula is OK as per logic you provided to it. You have to clear about both your requirement and what your are writing in your code. Your formula is returning exactly what you are instructing it.
If I understand correct, you simply need the Customer count for the Minimum Year. For say if you have 6 unique customer for Year 2019 and 11 unique customer for Year 2020, you are looking here for value 6 to return by your measure.
Now, what your summarize table actually returning? if you create a separate custom table for the Summarize code only as below, you can see the table will actually hold all your customer name/id in first column and the second column will hole the MIN year available for that customer.
orders_summarize =
SUMMARIZE(
Orders,
Orders[customer id],
"min_order_date_year",MIN(Orders[Order Date].[Year])
)
So basically you have list of all customer in your summarize table. And now your are counting rows of your summarize table which is actually returning the total number of unique customers.
Finally, if you wants customer count for a specific Year (like MIN year), follow these below steps-
Step-1: Create a custom summarized table as below-
store_summarized_table =
SUMMARIZE(
store,
store[Customer ID],
"mindate",MIN(store[Order Date])
)
Step-2: create a measure as-
count_cust_id = COUNT('store_summarized_table'[Customer ID])
Step-3: Now configure your Matrix visuals as shown in the below image. You can also get the output in the image-
To avoid the Physical Table, you can do this below-
Step-1: Create a Custom Column as below-
is_min_year =
// -- keep current row's customer id to a variable
VAR current_cust_id = store[Customer ID]
// -- keep current row's YEAR value to a variable
VAR current_year = store[Order Date].[Year]
// -- find the MIN YEAR from order date for the current row customer id
VAR min_year_current_custommer_id =
CALCULATE(
MIN(store[Order Date].[Year]),
FILTER(
store,
store[Customer ID] = current_cust_id
)
)
// -- check the current row's year is the MIN year of order date for the customer as well or not.
RETURN IF(current_year = min_year_current_custommer_id, 1,0)
OR create a measure as-
is_min_year_measure =
VAR min_order_year_for_current_customer =
CALCULATE(
MIN(store[Order Date].[Year]),
FILTER(
ALL(store),
store[Customer ID] = MIN(store[Customer ID])
)
)
RETURN
IF ( MIN(store[Order Date].[Year]) = min_order_year_for_current_customer, 1,0)
Step-2: Create a Measure as below-
For created Custom Column
count_cust_for_min_year =
CALCULATE(
DISTINCTCOUNT(store[Customer ID]),
FILTER(
store,
store[is_min_year] = 1
)
)
For Created Measure
count_cust_for_min_year =
CALCULATE(
DISTINCTCOUNT(store[Customer ID]),
FILTER(
store,
[is_min_year_measure] = 1
)
)
Now add "Order Date" and measure "count_cust_for_min_year" to your Matrix. The out put will same as below-
I want to create a DAX measure in PowerBI that will provide an aggregate of sales on a specific date.
I need that date to be controlled by a date slicer. Specifically the the maximum date on the slicer.
I would expect this to be a Calculate() function. So something like the following if it was hard coded with a date.
=CALCULATE(SUM(FactInternetSales2[Sales]), DimDate2[Dim Date] = DATE(2018, 06, 18))
But I need the filter component of the the Calculate() function (i.e , DimDate2[Dim Date] = DATE(2018,06,18)) to be dynamically populated from the max date on the date slicer. I understand, however that a measure can't be used as a filter in a calculate function - so I can't create a measure such as follows to identify the maximum date
=LASTDATE(DimDate2[Dim Date])
and then use it in the Calculate() function such as
=CALCULATE(SUM(FactInternetSales2[Sales]), DimDate2[Dim Date] = LASTDATE(DimDate2[Dim Date])
Can anyone outline how I can use the maximum date from the slicer to filter the Calculate() function, or achieve the same outcome?
A copy of my working file is located here
https://drive.google.com/file/d/1d1JiyPm1jOD9XkVqv3Q5pm0vk1FMotH9/view?usp=sharing
Cheers
Steve
You can read in the parameter value into a variable.
SalesSum =
VAR EndDate = LASTDATE ( DimDate2[Dim Date] )
RETURN
CALCULATE ( SUM ( FactInternetSales2[Sales] ), DimDate2[Dim Date] = EndDate )
You can use the Calculate() function with a filter like this:
=CALCULATE(SUM(Table1[SalesValue]), FILTER(Table1, Table1[Year] = 2019))
To get the value from a slicer you go to Modeling > New Parameter. Here you can specifie your parameter needs and hit OK. Now you gat a new table and column for this parameter on the fields pane. Just reference now on this column with the following code:
=SELECTEDVALUE(ParameterTable[ParameterValue])