average divided by the count per project - powerbi

I have three tables time, SectorProject, product Project.
Time AS(
SELECT *
FROM (VALUES(1011,48),(201,520),(36,120))V(id_project,time)),
SectorProject AS(
SELECT *
FROM (VALUES(1011,'BM'),(1011,'Fi'),(1011,'Om'),(201,'BM'),(36,'BM'))V(id_project,Sector1)),
prductProject AS(
SELECT *
FROM (VALUES(1011,'bike'),(1011,'velo'),(1011,'pc'),(201,'n'),(36, 'r' ))V(id_project,product))
I need to calculate average divided by the count per project
With sql server it will something like the following code:
avg( sum(time)) over (partition by t.id_project) * 1.0 / count(*) over (partition by t.id_project)
How to do the same thing within Dax.

You should look for "sum by category" to find the correct DAX pattern.
SumOverPartition:=
CALCULATE (
SUM ( T[Sales] ),
REMOVEFILTERS ( 'T' ),
VALUES ( T[Category] )
)
CountOverPartition:=
CALCULATE (
COUNTROWS ( T ),
REMOVEFILTERS ( 'T' ),
VALUES ( T[Category] )
)
You could also achieve it with ALLEXCEPT function but the pair REMOVEFILTERS and VALUE is better. Learnt the hard way.
https://www.sqlbi.com/articles/using-allexcept-versus-all-and-values/
In that article, they use the archaic name ALL instead of REMOVEFILTERS.
If you want it in calculated column, then you have to wrap it with another CALCULATE.
SumOverPartition:=
CALCUALTE
CALCULATE (
SUM ( T[Sales] ),
REMOVEFILTERS ( 'T' ),
VALUES ( T[Category] )
)
)

Related

Same column Date difference based on other field DAX POWER BI

I want to calculate the date difference for all values in Field1 based on Field2 for example datediff(3/1/2020-2/1/2020) based on Field2 (c-b).
I have tried several ways but no luck so far.
there is no minimum mentioned in the question, so i assume that you are looking for the difference of the previous stages.
Date Difference =
DATEDIFF (
CALCULATE (
MAX ( 'Table'[Date] ),
FILTER (
ALL ( 'Table' ),
'Table'[Date] < EARLIER ( 'Table'[Date] )
&& EARLIER ( 'Table'[Field1] ) = 'Table'[Field1]
)
),
'Table'[Date],
DAY
)
You can obtain a solution by adding 2 calculated columns:
First Calculated Column:
MinDate =
CALCULATE (
MIN ( YourTable[Date] ),
ALLEXCEPT ( YourTable, YourTable[Field1] )
)
2nd Calculated Column:
Date_Difference =
DATEDIFF ( [MinDate], [Date], DAY )
End Result:

How to extract sum of sales that have been reversed DAX

I need to manipulate the Sales measure to exclude any transactions which have been reversed.
Sales measure is as follows right now:
Sales ($) =
IF (
HASONEVALUE ( 'Currency'[Detail] ),
SUMX (
'Sales',
'Sales'[Value_Sold]
* CALCULATE ( VALUES ( 'Exchange Rates'[ExchangeRate] ) )
)
)
What steps and where would I add to extract Reversed Transactions from this measure? I tried below as that's what you'd do in EXCEL but that is not working - when pulling results, it can't display anything on the visual
Sales - Reversals ($) =
IF (
HASONEVALUE ( 'Currency'[Detail] ),
SUMX (
'Sales',
'Sales'[Value_Sold]
* CALCULATE ( VALUES ( 'Exchange Rates'[ExchangeRate] ) ) - SUMX ('Sales', 'Sales [Trans_Type] = "Reversed")
)
)
)
If what you want is to exclude the reversed transactions from your first code, maybe this could help:
Sales ($) =
IF (
HASONEVALUE ( 'Currency'[Detail] ),
CALCULATE(
SUMX (
'Sales',
'Sales'[Value_Sold]
* CALCULATE (
VALUES ( 'Exchange Rates'[ExchangeRate] )
)
),
'Sales'[Trans_Type] <> "Reversed"
)
)
It's basically adding the SUMX into a CALCULATE function which let's you make the some applied to filters (in this case not reversed transactions).

DAX - TOPN() in a SUMX() for multiple transactions

I need your help.
I am trying to make a calculated column which sum the sales for the last two dates (there are not sales on all dates!) for each product.
I have tried to use the calculation:
CALCULATE (
SUMX ( TOPN ( 2; 'Table'; 'Table'[date_ID] ); 'Table'[Sale] );
ALLEXCEPT ( Table; 'Table'[Product_ID] )
)
But this only works if you have one sale per date per product ID.
What do I do if there are many transactions per date and prod ID?
Below I have a table where I have (filtered) one date and one product.
Now, I have made a calculated column that sums all transactions per date and product ID (for reference).
This is
Calculated Column 2 =
CALCULATE (
SUMX ( Table; Table[Sale] );
ALLEXCEPT ( Table; 'Table'[Date]; 'Table'[Product_ID] )
)
Now comes the difficult part.
If I want to sum the transactions for the last two dates on each product, I have made the following calculation:
Calculated Column 1 =
VAR SumProd =
CALCULATE (
SUMX ( Table; Table[Sale] );
ALLEXCEPT ( Table; Table[Date]; Table[Product_ID] )
)
RETURN
CALCULATE (
SUMX ( TOPN ( 2; 'Table'; 'Table'[Date] ); SumProd );
ALLEXCEPT ( Table; Table[Product_ID]; Table[Date] )
)
The Problems:
The calculations sums ALL the values in each category
Example: in the table, you see "Calculated column 1"=7571200, which is 27040 * number of transactions? I only want the value 27040.
For some reason, the TOPN() doesn’t work. If I change the N_Value=2 to N_Value=3, the calculation doesn’t change?
Please, does anyone know what is wrong with my calculation?
Thanks.
Br,
Jakob
In your measure, SumProd is a constant that you're summing for each row in the table. This is not what you want.
I'd suggest something more like this:
Calculated Column 1 =
VAR LastTwoDates =
CALCULATETABLE (
VALUES ( Table[Date] );
TOPN ( 2; ALLEXCEPT ( Table; Table[Product_ID] ); Table[Date] )
)
RETURN
CALCULATE (
SUM ( Table[Sale] );
ALLEXCEPT ( Table; Table[Product_ID] );
Table[Date] IN LastTwoDates
)
In this, we first calculate a list of the top 2 dates associated with Product_ID and store it as a variable. Then we use that as a filter when calculating the sum of Sale.
I'm not positive this exact syntax will work, but I hope it will point you in a better direction.
It turns out my code didn't work exactly as intended. Try this instead:
Calculated Column 1 =
VAR ProductDates =
CALCULATETABLE (
VALUES ( Table1[Date] );
ALLEXCEPT ( Table1; Table1[Product_ID] )
)
VAR LastTwoDates = TOPN ( 2; ProductDates; [Date] )
RETURN
CALCULATE (
SUM ( Table1[Sale] );
ALLEXCEPT ( Table1; Table1[Product_ID] );
Table1[Date] IN LastTwoDates
)

Issue trying to calculate gradient using Power BI

I am trying to calculate the gradient of the trendline passing through a series of points contained within my dataset. I have researched to see if there are built in functions to do this and there doesn't seem to be, so I am doing it manually. I'm not a DAX expert (nor probably a maths expert either!).
I have created a table in excel to walk through a simple example so I know what I'm aiming for:
In the Power BI environment, there are two tables joined on the "Month&Year" columns. An abridged illustration of these tables is below:
Please note the "Orders" measure from the illustration is referred to as "Special orders per day" in the Power BI code.
Step 1
Create the measure that averages the month numbers:
Average of months =
- AVERAGEX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"AvMonths", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
[AvMonths]
)
I use AVERAGE in the expression part so that the record for Sept-2018 has a 21 in the "AvMonths" column and then for Oct-2018 it says 22. I guess I could have used MIN or MAX because they will all say 21 or 22 depending on the month (only one to avoid would be SUM as this would add them all up).
I also tried to do this by summarizing and then creating a NATURALLEFTOUTERJOIN to the User_Friendly_Months table to get the month number for these months and when incorporating that into the rest of this procedure the measure took forever to calculate (even though it actually worked in the end somehow).
Step 2
Do the same for orders:
Average of special orders =
- AVERAGEX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day]
),
[Special OPD]
)
Step 3
Perform the calculation that goes through to step "C" in my original picture:
Column_C_Step =
SUMX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day],
"MonthNum", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
( [Special OPD] + [Average special orders] )
* ( [MonthNum] + [Average of MonthNums] )
)
Instead of returning -11.95 in my example, the measure returns zero.
When I do this:
Check_orders_worked =
SUMX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day],
"MonthNum", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
[Special OPD]
)
...I get 1188.9, which is the total of "Orders" in my Excel table illustration (so must be working).
When I do this:
Check_months_worked =
SUMX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day],
"MonthNum", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
[MonthNum]
)
...I get 43, which is the total of Month_Num in my illustration (so again, must be working).
But when I attempt to perform the equivalent of a SUMPRODUCT on A and B to get C, it returns zero.
Can anyone shed any light on what on earth is going on??
It is driving me insane.
Or if there is a simpler way to do a gradient calculation I will cry with joy.
Thank you
UPDATE
For completeness here is the measure that worked:
Step_C_Measure =
VAR _OrdersAverage = [Average special orders]
VAR _MonthsAverage = [Average of MonthNums]
RETURN
SUMX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day],
"MonthNum", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
( [Special OPD] + _OrdersAverage )
* ( [MonthNum] + _MonthsAverage )
)
Then Step D:
Step_D_Measure =
VAR _MonthsAverage = [Average of MonthNums]
RETURN
SUMX (
SUMMARIZE (
CALCULATETABLE ( Query_GSR, ALLSELECTED ( User_Friendly_Months ) ),
Query_GSR[Month&Year],
"Special OPD", [Special orders per day],
"MonthNum", AVERAGE ( Query_GSR[MonthNumForSlope] )
),
( [MonthNum] + _MonthsAverage )
* ( [MonthNum] + _MonthsAverage )
)
And finally to get the gradient:
Special order gradient =
DIVIDE ( Step_C_Measure, Step_D_Measure, "" )
In a question about multiple linear regression, I linked to a community post that covers basic linear regression.
In your case, the formula for the slope can be calculated similar to this:
Slope =
VAR RowCount = COUNTROWS(Query_GSR)
VAR Sum_X = SUMX(Query_GSR, Query_GSR[Month_Num])
VAR Sum_Y = SUMX(Query_GSR, Query_GSR[Orders])
VAR Sum_XY = SUMX(Query_GSR, Query_GSR[Month_Num] * Query_GSR[Orders])
VAR Sum_XX = SUMX(Query_GSR, Query_GSR[Month_Num] * Query_GSR[Month_Num])
RETURN DIVIDE(RowCount * Sum_XY - Sum_X * Sum_Y, RowCount * Sum_XX - Sum_X * Sum_X)
This works for a regression on multiple months, not just two.

How do I calculate the sum of Value for the last 6 sprints using DAX

Problem:
I need a calculated measure in DAX that sums the Value column for the last 6 sprints. I am basing the last 6 sprints on the DimSprintEndDateKey in descending order.
Table structure in PowerBI
The DAX that I am using:
CALCULATE (
SUM ( factSprint[Value] ),
FILTER (
ALL ( factSprint ),
COUNTROWS (
topn(6,
FILTER (
factSprint,
EARLIEST( RELATED ( dimSprint[DimSprintEndDateKey] ) )
> RELATED ( dimSprint[DimSprintEndDateKey] )
),RELATED ( dimSprint[DimSprintEndDateKey] ), DESC
)
)
)
)
I am assuming that the relationship on your tables is between 'dimSprint'[dimSprintKey] and 'FactSprint'[dimSprintKey].
That being the case, this measure could work for you.
Total Value Last Six Sprints =
VAR endDateSprint =
LOOKUPVALUE (
'dimSprint'[dimSprintEndDateKey],
'dimSprint'[dimSprintKey], SELECTEDVALUE ( 'FactSprint'[dimSprintKey] )
)
VAR dimTableFiltered =
FILTER ( 'dimSprint', 'dimSprint'[dimSprintEndDateKey] <= endDateSprint )
RETURN
CALCULATE (
SUM ( 'FactSprint'[Value] ),
ALL ( 'FactSprint' ),
TOPN ( 6, dimTableFiltered, [dimSprintEndDateKey], DESC )
)
Use it on a matrix visual (or pivottable). Be sure to put 'FactSprint'[dimSprintKey] or 'FactSprint'[SprintPK] on Rows and [Total Value Last Six Sprints] on Values.