Maximize sum of (n-combination) rows with constraint - powerbi

I have a table with 3 columns: Product, Cost, Revenue.
There are 1000 rows (1000 distinct Products).
My budget equals B.
I want to filter 3 Products so that I maximize the Revenue sum for those 3 products, provided that the total Cost for those 3 Products are less than my budget B.
Can this be done in Power BI?
I would appreciate any kind of help.
Thank you in advance.
Best Regards.

As you didn't share any sets of data, I created a scenario with datasets. I hope It is similar to your case:
Please note that if you want to paste the code into your Power BI Desktop, please remember to remove "evaluate" statement. Also Table functions require you to create a new table to see the results unless you plan to use them as table expressions in your DAX code.
First create a table:
DEFINE
TABLE FactTable =
SELECTCOLUMNS ({
(102, 12.5, 14.5),
(103, 20.5, 21.5),
(104, 12.5, 13.0),
(105, 23.5, 25.5),
(106, 12.0, 15.0),
(107, 10.0, 14.0),
(108, 16.5, 18.5),
(109, 25.0, 28.0),
(110, 12.5, 18.0),
(111, 14.5, 16.5),
(112, 15.5, 17.5)
},
"Product",[Value1],
"Cost", [Value2],
"Revenue",[Value3])
VAR MyBudget = 50.0
EVALUATE
FactTable
Now let's make some tests:
Most profitable products are the ones where [Revenue] - [Cost] are the greatest. Lets find out which products they are:
Code to test Top3 highest [Revenue] - [Cost] values:
TOPN (3,FactTable,[Revenue]- [Cost])
Note: Ties are included. That's why there are 4 rows.
Now let's find the most costly products:
TOPN (3,FactTable,[Cost])
Now It is time to build filter context of calculate. I mean we need to find the products where [Revenue] - [Cost] is greatest, and [Cost] is among the lowest sets of values. We will use EXCEPT() function in DAX.
EXCEPT(
TOPN (3,FactTable,[Revenue]- [Cost]),
TOPN (3,FactTable,[Cost]))
Let's test now if top 3 [Cost] values are less than my budget.(Here we are checking it against our variable "MyBudget= 50")
EVALUATE
ROW("Top3 Total Less Than My Budget",SUMX(
EXCEPT(
TOPN (3,FactTable,[Revenue]- [Cost]),
TOPN (3,FactTable,[Cost])),
[Cost]
)<= MyBudget)
And finally, since our test result is "True", we can write our final code to calculate the top3 revenue total using calculate function:
EVALUATE
ROW("Top3 Total Revenue", CALCULATE(SUM(FactTable[Revenue]),
EXCEPT(
TOPN (3,FactTable,[Revenue]- [Cost]),
TOPN (3,FactTable,[Cost]))
))
Comparison:
I hope It can be helpful for you.

Related

PowerBI - How to count same values from multiple columns

This is my first question here.
This time I want to count values that appear in different columns. Each one corresponds to the values from a row, but there is only 1 column that they have in common (not shown in the picture). I need a measure to show a count of each word described in those cells.
For example, in this case (please ignore blanks, it's a test), the measure should give a count for the word 'Desodorante' as 3, 'Cabello' as 2, and the rest 1. These words are pre defined and there are no random values accepted.
I may say that I want to state each of these words as a kind of category. I would like to make a slicer out of them too.
example
I believe a workaround is to create a calculated table, stating as columns each of these values and allocating a count of each value from these 4 columns?
A Power Query solution to this problem has been posted here: PowerBI - Count instances of string in multiple columns
A DAX solution to this problem would be to create a new calculated table by appending the 4 columns using UNION() and SELECTEDCOLUMN() and then getting the count via SUMARIZE():
The 2 calculated Tables:
Mesa =
FILTER(
UNION(
SELECTCOLUMNS(
'Ramiro',
"Producto", 'Ramiro'[Producto]
),
SELECTCOLUMNS(
'Ramiro',
"Producto", 'Ramiro'[Producto2]
),
SELECTCOLUMNS(
'Ramiro',
"Producto", 'Ramiro'[Producto3]
),
SELECTCOLUMNS(
'Ramiro',
"Producto", 'Ramiro'[Producto4]
)
),
[Producto] <> BLANK()
)
Producto Count =
SUMMARIZE(
'Mesa',
'Mesa'[Producto],
"Count", COUNT('Mesa'[Producto])
)

Calculating the percentage of grand total by category with DAX for one category only

I need help calculating the percentage of each category in a column (based on the grand total) in DAX but for one specific category.
This is how the data is structured. Each row is an individual transaction with an ID column and item column.
I need to get the % of transactions that are for bagels only. This is my sql code I currently use.
`Select 100 - CAST(count([Items])
- count(case [Items] when 'Bagel' then 1 else null end) AS FLOAT)
/ count([Items]) * 100 as Percent_Bagel
from Items_Table where Items != 'Coffee'
and Items != 'Muffin'`
I need this to be converted to a DAX formula to use in a Power BI measure if possible, but I am new to DAX and don't know where to begin.
Thank you.
The "right" implementation for you always depends on the context. You can achieve your goal through different approaches.
I have used the following:
Measure =
DIVIDE(
-- Numerator: Filter all Bagel's transaction and count them
CALCULATE(
COUNT('Table'[Transaction ID]),
FILTER('Table', 'Table'[Item] = "Bagel")
),
-- Denominator: Remove any filter - essentially fixing the full table - and count all transactions we have
CALCULATE(
COUNT('Table'[Transaction ID]),
ALL('Table'[Item])
),
-- If something goes wrong with the DIVIDE, go for 0
0
)
You may also use the filters to rule out all measures that are not blank.
Without measure filter
With measure filter (Other categories are gone)
Hope this is what you are looking for!

Calculate the average of the median %-change per product using only a measure in DAX

I need to perform a simple calculation in DAX that consists of 2 steps.
Step 1: Calculate the median price change (%) per product.
Step 2: Calculate the average of all the medians calculated in Step 1 while counting each product (calculated median) only once.
Using a calculated column for Step 1 doesnt seem to work out for me because the medians from Step 1 are subject to change as soon as the user filters the table (i.e. using a date slicer) in the report.
Therefore, I will need to get both Steps performed dynamically in a measure.
I'm pretty sure the answer to: "Is there any way to achieve this?" will be "Yes". I just lack the know-how at this point and can't seem to find the answer.
I would recommend to create 2 differents measures to solve this problem.
But since you need to create only 1 measure you can use the following DAX function:
Median_per_product =
VAR __step1 = CALCULATE( MEDIAN('Table'[Price_Change] ), ALLEXCEPT('Table', 'Table'[Product] ))
VAR __step2 = AVERAGEX( VALUES( 'Table'[Product] ), CALCULATE( MEDIAN( 'Table'[Price_Change] ) ) )
RETURN
IF(
HASONEVALUE('Table'[Product]) &&
NOT(ISBLANK( __step1 )),
__step1,
__step2
)
This is the expected result:

How to divide each row of a calculated column by the total of another calculated column?

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"
)
)

DAX - Grand Total not adding up to Row Total

I have a powerbi report which is running a dax formula to calculate a custom measure. In the picture below, the total at the bottom doesn't seem to add up to the individual rows. I've been trying my luck for some time and can't seem to figure out why this is.
The DAX formula used is as follows
SumRest<24hrs7Day = CALCULATE(
DISTINCTCOUNT(WorkTimeDirective[EmployeeKey]),
FILTER(
ADDCOLUMNS(
SUMMARIZE(WorkTimeDirective,Employee[EmployeeKey],'Date'[DateKey]),
"totRestHrs", CALCULATE(MAX(WorkTimeDirective[RestHours])
,DATESINPERIOD('Date'[DateKey], LASTDATE('Date'[DateKey]), -7, DAY))
),
[totRestHrs]<24
),
WorkTimeDirective[IsEmployeeAbove18]=1
)
Any idea why this is and what I am doing wrong.
For using SUMX the main step is listing the values which you are iterating over, which it typically a table or column. In this case it sounds like you would do a column.
For the example I just had it call the measure you already defined, since breaking DAX calculations into smaller pieces makes writing/testing complex formulas easier.
The idea being that it would iterate over the unique values which are in your TableName[Site Name], then run the [SumRest<24hrs7Day] under that context. I used TableName for the table due to not knowing the name for the table.
SUMX_Example = SUMX( VALUES( TableName[Site Name], [SumRest<24hrs7Day])