Difference between SUMX and Calculate in DAX Language for this specific example - powerbi

I have the following two DAX Commands, who seem to be giving different results,
First DAX command
FourLeggedSales = SUMX(
FILTER(Purchase, RELATED('Product'[Legs]) = 4),
Purchase[Quantity]
)
Second DAX Command,
FourLeggedSales = CALCULATE( SUM(Purchase[Quantity]), 'Product'[Legs] = 4)
The second DAX Command is given in the solution file and apparently gives correct results. While the first one was what I wrote and it is giving wrong results.
Can anyone help me understand what's causing the issue here?
Additional Information if Needed
Just to be clear, I am solving this problem of DAX here: https://www.wiseowl.co.uk/power-bi/exercises/dax/filtering/4094/
You can find the Example Workbook from the link provided as well (with the dataset)
^These are the two example DAX Commands I gave here.
Complete DAX Measure that I created is as given (it doesn't give correct results)
Ratio =
var FourLeggedSales = SUMX(
FILTER(Purchase, RELATED('Product'[Legs]) = 4),
Purchase[Quantity]
)
var SixLeggedSales = SUMX(
FILTER(Purchase, RELATED('Product'[Legs]) = 6),
Purchase[Quantity]
)
var SumOfSales = FourLeggedSales + SixLeggedSales
var ManyLeggedRatio = DIVIDE(SUMX(Purchase,Purchase[Quantity]), SumOfSales, 0)
Return ManyLeggedRatio
The result of the measure I created is as given,
The Measure created in the Solution File is as below,
FourLeggedRatio =
VAR SalesFourLegs = CALCULATE( SUM(Purchase[Quantity]), 'Product'[Legs] = 4)
VAR SalesSixLegs = CALCULATE( SUM(Purchase[Quantity]), 'Product'[Legs] = 6)
VAR ManyLeggedRatio = DIVIDE(SUM(Purchase[Quantity]) , (SalesFourLegs + SalesSixLegs))
RETURN ManyLeggedRatio
Result of the Measure in the Solution File is as given,

Related

Power Bi DAX - Calculating Workingdays from a past period

I´m really struggling about the following problem, searched a lot, tried a lot but still I´m not able to achieve my goal. I really hope, that someone can help me out with this.
Situation
I´ve created a meassure:
Measure =
VAR selYear = SELECTEDVALUE('Stats Param LindyCalendar'[Date].[Year])
VAR selMonth = SELECTEDVALUE('Stats Param LindyCalendar'[Month])
VAR selDay = day(now())
VAR enddate = DATE(selYear, selMonth, selDay)
VAR CurWorkingDay =
COUNTROWS(
FILTER(
FILTER('Stats Param LindyCalendar', 'Stats Param LindyCalendar'[Date].[Date] <= enddate),
'Stats Param LindyCalendar'[WorkingDay_YN] = -1))
RETURN CurWorkingDay
There are three slicers. The first one is based on Country-Table which has correct working relationships to all needed tables. It just filters the Country.
The second slicer is based on 'Stats Param LindyCalendar'[Date].[Year].
The last one is based on 'Stats Param LindyCalendar'[Date].[Month].
When I play around with the slicer, setting random values, it works fine.
Goal:
I want to get back the CurWorkingDay of the last year.
So I did:
VAR selYear = SELECTEDVALUE('Stats Param LindyCalendar'[Date].[Year])-1
The result is "Blank" in the Card-Visual.
That´s my problem, and I don´t know how to fix that.
Would be great if someone could provide a solution or hint.
Thanks a lot in advance.
Finally I got it.
workingdays_MTD =
VAR selYear = SELECTEDVALUE('Stats Param LindyCalendar'[Date].[Year])-1
VAR selMonth = SELECTEDVALUE('Stats Param LindyCalendar'[Month])
VAR selDay = day(now())
VAR enddate = DATE(selYear, selMonth, selDay)
VAR test =
TOTALMTD(COUNTROWS('Stats Param LindyCalendar'),'Stats Param LindyCalendar'[Date].[Date] = enddate,'Stats Param LindyCalendar'[WorkingDay_YN] =-1)
RETURN test
Power BI marks an error for "'Stats Param LindyCalendar'[Date].[Date] = enddate," but it works anyway...

DAX Flag in Matrix Visual - Multiple levels of analysis

I replicated an issue I am having with the 'Adventure Works DW 2020' pbix file, so if my analysis seems a little out of context, please understand this example is not the true data I am working with. The pbix I used can be downloaded here:
https://drive.google.com/file/d/1vn6CluiE5rrAF3UjYPh5ejb93H2JX6IX/view?usp=sharing
My goal is to create a measure that can flag the subset of records that I want to use for a matrix visual.
I created the following measure with notes in the syntax:
VAR TABLEVAR =
SELECTCOLUMNS(
FILTER(
SUMMARIZE(
CALCULATETABLE(Sales/*Apply several filters to Sales table*/
,NOT Sales[CustomerKey] = -1
,Sales[orderdatekey] > 20180731
,Sales[orderdatekey] < 20190601
)
,[CustomerKey]/*Count the number of products per customer*/
,"Count",COUNT(Sales[ProductKey])
)
,[Count] > 1/*Only keep customers that bought more than 1 product*/
)
,[CustomerKey] /*Select the identifiers of the desired customers*/
)
RETURN
{
SWITCH(TRUE()
,SELECTEDVALUE(Sales[CustomerKey]) IN TABLEVAR/*Flag the customers that were identified in the previous table*/
,1,BLANK()
)
}
Now, in the PowerBI Matrix visual, this seems to work at first:
I had successfully flagged the desired output. Now I just have to filter for the 'Analysis' measure to be 'Not Blank', but then this happens:
Now removing that filter and going down a level:
So you see, the measure does not evaluate at the record level of the table. Does anyone understand the concept I am missing here? I have tried all kinds of different measures but it all comes down to the same problem about flagging different levels of analysis.
Ideally, the output would only include the following(circled in green):
These are the records that are within the date filters I put into the CALCULATETABLE() arguments.
Any help or insight with this problem would be greatly appreciated. Thank you
I'm not 100% clear what you're trying to do but please try the following and see if it helps.
Analysis =
VAR TABLEVAR =
SELECTCOLUMNS(
FILTER(
SUMMARIZE(
CALCULATETABLE(Sales
,NOT Sales[CustomerKey] = -1
,Sales[orderdatekey] > 20180731
,Sales[orderdatekey] < 20190601,
REMOVEFILTERS()
)
,[CustomerKey]
,"Count",COUNT(Sales[ProductKey])
)
,[Count] > 1
)
,[CustomerKey]
)
RETURN
//CONCATENATEX(TABLEVAR, [CustomerKey], ",")
SWITCH(TRUE()
,SELECTEDVALUE(Sales[CustomerKey]) IN TABLEVAR
,1,BLANK()
)

Comparison between previous week and current week total sales in powerBi

I am very new to the PowerBI community and I am confused about how to visualize and create measures/columns for the data which requires comparing last week/month/year data with respect to the current week.
I have tried various solutions available on the internet or other forums. I would appreciate it if anyone can please outline the steps required to achieve the goal.
The data that I have is transactional data and I have also created a Date Table. I am not sure how to go ahead with the problem.
You can create measures like this (for days):
PreviousDay =
var __DayOnRow = SELECTEDVALUE(Calendar[day])
return
CALCULATE( SUM(Table[SomethingToSum]), FILTER(ALL(Calendar),Calendar[day] = __DayOnRow -1 ))
How this work:
SELECTEDVALUE gets a specific day from the current context
__DayOnRow -1 give us a previous Day (not yesterday date< except for today date>)
FILTER with ALL, remove every filter on Calendar (current row is also a filter, so without removing filter we get two excluding conditions )
How do that for WEEK?
PreviousWeek =
var __WeekOnRow = SELECTEDVALUE(Calendar[Week])
var __FirstDayOfWeek = calculate(min(Calendar[Day]), FILTER(ALL(Calendar), __WeekOnRow = Calendar[Week] ))
var __LastDayOfWeek = calculate(max(Calendar[Day]), FILTER(ALL(Calendar), __WeekOnRow = Calendar[Week] ))
return
CALCULATE(SUM(Table[SomethingToSum]), FILTER(ALL(Calendar),Calendar[day] >= __FirstDayOfWeek -7 && Calendar[day] <= __LastDayOfWeek -7 ))

How to get TOPN in DAX ignoring duplicate values

Using filter to get Top 5 by Submitted.
However it gives me more than 5, due to duplicates.
How can I tweak or create a measure that would only give me top 5 disregarding duplicates.
I tried to use RANK function but also no success:
Rank = RANKX ( ALLSELECTED ( Policy[CodeDescription] ), CALCULATE ( SUM ( Policy[Submitted]) ) )
You can create a new column and add "Submitted" + RAND() and then rank it based on the new column. Considering you don't have a preference as to which column value gets priority.
Check out the below link for more options:
https://www.red-gate.com/simple-talk/sql/bi/cracking-dax-the-earlier-and-rankx-functions/
I was able to solve it by using below measure:
Top 5 Code filter =
VAR toprank = RANKX(ALLSELECTED(Policy[CodeDescription]), CALCULATE(SUM(Policy[Submitted]) + MAX(Policy[ControlNo]) * 0.0000001),,DESC,Dense)
RETURN
toprank
enter image description here
Below query helped to resolve this issue.
Top 5 Code filter =
VAR toprank = RANKX(ALLSELECTED(gict_riskregisterdetail), CALCULATE(SUM(gict_riskregisterdetail[PICost_RbM_Rnk]) + MAX(gict_riskregisterdetail[Number]) * 0.0000001),,DESC,Dense)
RETURN
toprank

CALCULATE with OR condition in two tables

In order to Sum the sales amount of blue products OR products that belong to category shoes, I'm using the following DAX expression:
CALCULATE(
SUM(Table[SalesAmount]),
FILTER(
Table,
Table[Color] = "Blue" ||
Table[Category] = "Shoes")
)
However, this doesn't work with two different tables (Colors and Categories), like:
CALCULATE(
SUM(Table[SalesAmount]),
FILTER(
Table,
Colors[Color] = "Blue" ||
Categories[Category] = "Shoes")
)
Can anyone help?
Thanks!
Searching the web led me to this forum topic. Borrowing from OwenAuger's post, I propose the following formula:
CALCULATE(SUM(Table[SalesAmount]),
FILTER(SUMMARIZE(Table, Colors[Color], Categories[Category]),
Colors[Color] = "Blue" ||
Categories[Category] = "Shoes"))
We get around the single table restriction by using SUMMARIZE to create a single table that has all of the pieces we need.
This might not be the ideal answer, but one way to do this is to use the inclusion-exclusion principle:
CALCULATE(SUM(Table[SalesAmount]), Colors[Color] = "Blue") +
CALCULATE(SUM(Table[SalesAmount]), Categories[Category] = "Shoes") -
CALCULATE(SUM(Table[SalesAmount]), Colors[Color] = "Blue", Categories[Category] = "Shoes")