I'm using a simple table like this to make a report in Power BI:
Order number
Order date
Turnover
001
30/1/2022
10 €
002
30/1/2022
20 €
003
2/2/2022
15 €
I need to create a line chart showing all the dates, even where I have no data (no orders for that day). This is currently how is shown:
You can notice that the 1/2/22 and 3/2/22 are missing due to no order, but I want them to be visible and the value should be 0. This is also affecting the average line because it's calculated based on the days with data, but I need to put into account also the 0-turnover days.
I tried to use the "Show items with no data" on the date dimension and switch the X axis from Continuous to Catergorical and the other way around. I also tried to create a new metric like this:
Total Turnover = IF(ISBLANK(SUM(Orders[Turnover (EUR)])), 1, SUM(Orders[Turnover (EUR)]))
but it's not working.
If I understand your business requirement correctly, you are going to need to do three things:
Make sure you have a date-dimension table in your model. Build the relationship based on your [Order date] column.
Refactor your [Total Turnover] measure as such:
Total Turnover =
VAR TotalTurnover = SUM( Orders[Turnover] )
RETURN
IF(
ISBLANK( TotalTurnover ),
0,
TotalTurnover
)
Build your line chart using the [Date] column from your date table.
Related
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.
I am using power BI and I would like to create a line chart which contains values from two tables (sales history and sales prediction). So for the past 12 months, the line should reprensent the sales history and for the next 6 months, the line reprensents sales prediction. Here is what the data looks like, lets say we are in June 2021:
I know there is a way to do it in DAX but I don't know how to do it by myself. Thanks a lot in advance for your help !
You can achieve this by
Delete any relationship between Calendar and the other two tables if there is any, as we are going to use DATESBETWEEN function to calculate
Create two metric like below, you might need to adjust the column names as per your project
Sales History Amount = IF('CALENDAR'[Date] <= TODAY(), CALCULATE(SUM('Sales History'[Amount]), DATESBETWEEN('Sales History'[Date], MIN('CALENDAR'[Date] ), MAX('CALENDAR'[Date]))), BLANK())
Sales Prediction Amount = IF('CALENDAR'[Date] >= TODAY(), CALCULATE(SUM('Sales Prediction'[Amount]), DATESBETWEEN('Sales Prediction'[Date], MIN('CALENDAR'[Date] ), MAX('CALENDAR'[Date]))), BLANK())
Add these two metrics in the table and use the Date from the Calendar table as X axis.
Format the first metric to solid line, and dash line for the second
Calendar should be linked to your tables.
Prediction Amount =
VAR lastSalesDate = MAX('Sales History'[Date])
VAR currentPredictionAmnt =
CALCULATE(
SUM('Sales Prediction'[Amount])
,KEEPFILTERS('CALENDAR'[Date]>lastSalesDate)
)
RETURN currentPredictionAmnt + SUM()
Sales Amount =
SUM('Sales History'[Amount])
I have a table like shown below:
ID
Date
Asset
Location
145
7/29/22
A
Market
145
7/30/22
A
Warehouse
145
7/29/22
B
Market
145
7/29/22
C
Truck
150
7/30/22
B
Market
145
7/29/22
D
Market
145
7/30/22
A
Market
What I am trying to accomplish is to get a distinct count of IDs for each date with a location filter as well. So I would want a count of ID based on the slicer selected Date of 7/29/22 AND 7/30/22 for the Market Location. The desired result is 2 for the selected dates from the date slicer which directly corresponds to the date column in the table.
I was trying to use this DAX formula and wasn't getting anywhere....
IDsMarket =
CALCULATE (
DISTINCTCOUNT ( 'Products'[ID] ),
ALL ( 'Products' )
)
I have a measure dropped onto a card. I should have specified that. My apologies. I need 1 measure to show me the combined count for the two days selected.
I tried this with countrows as well but of course the result wasn't distinct... Any help would be greatly appreciated!!
The formula you're looking for is
IDsMarket =
CALCULATE(
DISTINCTCOUNT('Products'[ID]),
'Products'[Location] = "Market"
)
The resulting Table will look like this
But if you put the measure on a Card visual, you'll get
So in DAX the same measure can yield 1000 different values - depending on the filter context.
I created a conditional column in Power Query and combined the ID with the "day" number from the date column which allowed me to then do a distinct count on that combined custom column which produced to correct answer. Sorry for all the confusion. One of those days.
I can't get a division correct with this sample data:
Calculated column Another calc. column
48 207
257 370
518 138
489 354
837 478
1,005 648
1,021 2,060
1,463 2,164
2,630 1,818
2,993 2,358
3,354 3,633
4,332 5,234
4,885 6,108
4,514 6,008
4,356 6,888
4,824 7,382
7,082 5,988
7,498 6,059
4,865
4,192
3,816
2,851
2,768
2,093
2,207
770
397
149
178
336
167
124
18
What I'm trying to do is to create a new calculated column.
For each row I want to get the value of Calculated column and divide it by the Total of Another calc. column.
The Total of Another calc. column = 82826
This is the desired output in a brand new calculated column, let's call it % Column:
% Column
0,000579528167484
0,003102890396735
0,006254074807428
.
.
.
NOTE - these 3 columns: Calculated column, Another calc. column and % Column are all in the same table and are all calculated columns.
I tried lots of formulas but not a single one returned the desired output. :| I guess it's because of the nature of calculated columns or I'm not getting the gist of it.
Is this even possible or I should follow another path using a Measure?
Can you shed some light?
####### EDIT #######
I put together a sample file to help debugging this. Here it is:
https://drive.google.com/open?id=1r7kiIkwgHnI5GUssJ6KlXBAoeDRISEuC
As you see:
Earned Daily % HARDCODED works just fine because 82826 is hardcoded as the denominator.
Earned Daily % by StelioK and Earned Daily % by Alexis Olson output the same wrong value for the division when using SUM formula.
I'm using the latest Power BI Desktop version if that matters: Version: 2.70.5494.701 64-bit (June 2019)
Basically, there is nothing wrong with the calculated columns, and both Alexis and StelioK formulas are correct.
The root problem here is a confusion between calculated columns and measures. You are looking at the results in a conceptually wrong way - through the matrix visual, with several filters active on slicers. If you remove the filters, you will see that the total amount is 140,920, not 82,826. The latter number is the total for the filtered data set, not the entire table.
To get this right, you need to understand several fundamental concepts behind Power BI:
Calculated columns are always static. Once a calculation is
completed, it can not respond to slicers or other UI controls. It's
just static data, identical to data in non-calculated columns. DAX
formulas used to calculate columns are active only when you create
them, or upon data reload.
If you want your calculations to respond to slicers etc, they must be measures. It's the only way, no exceptions.
Avoid calculated columns, they are utterly useless. Power BI is all about measures; I can't think of a single reason for using calculated columns. When you add a column, you are essentially enhancing your source data, because you feel like you are missing something you need for your report. But that need can be much better addressed at the source (database or file you import), or using Power Query, which is designed exactly for this kind of tasks. The best practice is: build your columns at the source, for everything else design measures.
Another important advice: never drop fields (columns) into visuals directly. Always write a DAX measure, and then use it. Relying on Power BI auto-aggregations is a very bad practice.
You can do this by using the following DAX:
% Column =
VAR TotalSum =
SUM ( 'Table'[Another Calc column] )
RETURN
IF (
NOT ( ISBLANK ( 'Table'[Calc Column] ) ),
CALCULATE ( DIVIDE ( SUM ( 'Table'[Calc Column] ), TotalSum ) ),
0
)
Which yields the following:
I Hope it helps!!
For me the following works:
DIVIDE( Table1[Calculated column], SUM(Table1[Another calc column]) )
If that's not working, I'd need to see a file where you can reproduce the problem.
Edit: After looking at your file, the total of 82,826 is only true with the filters you've selected.
Note that calculated columns are not dynamic and cannot be responsive to filters since they are calculated only when the table is first loaded.
If you need it to be dynamic, then write it as a measure more like this:
Earned Daily =
DIVIDE (
CALCULATE (
SUM ( 'Test data'[Value] ),
'Test data'[Act Rem] = "Actual Units",
'Test data'[Type] = "Current"
),
CALCULATE (
SUM ( 'Test data'[Value] ),
ALLSELECTED ( 'Test data' ),
'Test data'[Act Rem] = "Remaining Units",
'Test data'[Type] = "PMB"
)
)
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
)