PowerBI join table and calculation - powerbi

I have two tables:
Table 1
Year Name Score
2010 A 1000
2011 A 1200
2012 A 1200
2013 A 1300
2010 B 1100
2011 B 1500
2012 B 1300
2013 B 1600
Table 2
Year Factor
2010 3.57
2011 4.21
2012 6.11
2013 2.15
I would like to do this: match two tables, as long as Year in Table 1 match Year in Table 2, divide the score by the factor, e.g. for A in 2010, 1000/3.57; for B in 2010,1100/3.57
How to revise the following code?
adjusted score =
VAR
filter (all('Table 1'[Year]), 'Table 1'[Year]='Table 2'[Year])
RETURN
DIVIDE ('Table 1' [Score], 'Table 2'[Factor')
Thank you very much!

If you are looking for a measure, you can try this below code-
adjusted score =
VAR current_row_year = MIN('Table 1'[Year])
VAR current_row_Score = MIN('Table 1'[Score])
VAR factor =
CALCULATE(
MAX('Table 2'[Factor'),
filter (
all('Table 2'),
'Table 2'[Year]= current_row_year
)
)
RETURN DIVIDE (current_row_Score, factor)
Code for a Custom Column is as below-
adjusted score =
VAR current_row_year = 'Table 1'[Year]
VAR current_row_Score = 'Table 1'[Score]
VAR factor =
CALCULATE(
MAX('Table 2'[Factor'),
filter (
all('Table 2'),
'Table 2'[Year]= current_row_year
)
)
RETURN DIVIDE (current_row_Score, factor)
You can also do the same using Transformation using Power query. In that case you have to just merge your table 1 and 2 using Year and then after Expanding the table, you will have Factor in each row for the Year. You can then just add a new custom column with - Score/Factor

Related

How can i get the value of a column for the max avalaible date when the selected date in the filter is bigger than the max date avalaible

lets say i have a table1 with three products and the max date i have available data for each one
product
max_date_aval
milk
13/9/2022
paper
15/9/2022
oranges
15/9/2022
a table2 with the product name, the rec_date and the sales amount
rec_date
product
sales
12/9/2022
milk
13
12/9/2022
paper
10
12/9/2022
oranges
11
13/9/2022
milk
12
13/9/2022
paper
14
13/9/2022
oranges
16
14/9/2022
paper
17
14/9/2022
oranges
9
15/9/2022
paper
12
15/9/2022
oranges
11
and a typical calendar date that i use as a filet in my dashboard.
I have created a table that displays the three products and the sales like this ( when i choose "13/9/2022" in the date filter)
product
daily_sales
MTD
milk
12
300
paper
14
329
oranges
16
321
what i want to achieve is that, when i choose a date in the filter that its bigger than the max available date, i want the table to display the value for the maximum date i have availiable.
For example, if i choose "14/9/2022" in the filter, i want th e table to be like this
product
daily_sales
MTD
milk
13
300
paper
17
346
oranges
9
330
Currently what im getting is the one bellow ( which makes sense but i need to have all three products )
product
daily_sales
MTD
paper
17
346
oranges
9
330
In order to achieve this, the dates used within the slicer need to be unrelated to the other two tables.
You can do this by either manually removing/deactivating the relationship between the Table2 and Calendar tables and then replacing your current Sales measure with the following:
MyMeasure1 :=
VAR SelectedDate =
MIN( Celandar[Date] )
VAR MaxAvailableDate =
CALCULATE(
MAX( Table1[max_date_aval] ),
Table1[max_date_aval] <= SelectedDate
)
VAR DateToUse =
IF( ISBLANK( MaxAvailableDate ), SelectedDate, MaxAvailableDate )
RETURN
SUMX( Table2, IF( Table2[rec_date] = DateToUse, Table2[sales] ) )
or, if you prefer to leave that relationship active, it can be deactivated in-measure:
MyMeasure2 :=
VAR SelectedDate =
MIN( Celandar[Date] )
VAR MaxAvailableDate =
CALCULATE(
MAX( Table1[max_date_aval] ),
Table1[max_date_aval] <= SelectedDate
)
VAR DateToUse =
IF( ISBLANK( MaxAvailableDate ), SelectedDate, MaxAvailableDate )
RETURN
CALCULATE(
SUMX( Table2, IF( Table2[rec_date] = DateToUse, Table2[sales] ) ),
CROSSFILTER ( Celandar[Date], Table2[rec_date], NONE )
)

Power BI DAX - Dynamically Calculate Distinct Count of Patients with Most Recent Value Less Than 9

I have a table of a1C values structured in this way:
patientID Result_Date Value
A 1/1/2021 5
B 3/3/2021 9
C 5/5/2021 4
A 3/1/2021 9
B 6/1/2021 13
A 7/1/2021 4
C 4/8/2022 12
etc...
I need to create a DAX measure that will dynamically calculate the distinct count of patients who have a value less than 9 as their last value as well as the distinct count of all patients in the population from the past 12 months of whatever date range is filtered. This is so I can calculate % a1c < 9. I have a calendar table in this data model so the idea is that as a user selects a fiscal month, the measure would dynamically calculate the % of distinct patients with an a1C less than 9 as their latest value over the past 12 months. I cannot share the actual dataset per HIPAA
Here are a few examples of the work I tried to do just to get a table of patients with their most recent date and most recent value as I figure that is the first step. I have been unsuccessful. Thank you for any help you can provide!
VAR summaryTable =
VAR patientID = VALUES(A1c[patientID])
VAR results = FILTER(A1c, A1c[patientID] = patientID)
VAR MaxDate = CALCULATE( MAX(A1c[Result_Date]), results)
RETURN
CALCULATETABLE(A1c, FILTER(results, A1c[Result_Date] = MaxDate)
/*ADDCOLUMNS(SUMMARIZE(A1c, A1c[patientID], "ValueDate", MAX(A1c[Result_Date]))
// , "LastValue", LOOKUPVALUE(A1c[Value_Formatted], A1c[Result_Date], FORMAT("ValueDate", "MM/DD/YYYY"), A1c[patientID], "patientID"))
// does not run due to formatting of columns; attempted to format but still doesn't work
//ADDCOLUMNS(VALUES(A1c[patientID]), "ValueDate", MAX(A1c[Result_Date]))
/* ADDCOLUMNS (
VALUES ( A1c[patientID] ),
"#outer val",
SELECTCOLUMNS (
TOPN ( 1, 'A1c', MAX(A1c[Result_Date]) ),
"#val", 'A1c'[Value_Formatted]
)) */)
lessThanNine =
VAR patientlastDates=
ADDCOLUMNS(
VALUES(tbl[patientID])
,"lastdate",LASTDATE(tbl[Result_Date])
)
VAR patientLastValue =
ADDCOLUMNS(
patientlastDates
,"lastValue", VAR currentP=[patientID]
VAR currentD=[lastdate]
RETURN
CALCULATE(
MAX(tbl[Value])
,tbl[patientID]=currentP
,tbl[Result_Date]=currentD
)
)
VAR filtered=
FILTER(
patientLastValue
,[lastValue]<9
)
RETURN
COUNTROWS(filtered)
Distinct count as below:
patientsWithinTimeFrame=
IF(
ISFILTERED('tbl'[Result_Date])
,COUNTROWS(VALUES('tbl'[patientID]))
,COUNTROWS(
CALCULATETABLE(
VALUES('tbl'[patientID])
,DATESINPERIOD(
'tbl'[Result_Date]
,MAX('tbl'[Result_Date])
,-1
,year
)
)
)
)

mdxscript(model) (24 9) Power BI

I've been trying to calculate stores' first 10 years of annual sales since their unique inception date.
My Yr1 Sales measure is working correctly
[results for Yr1 Sales][1]
and its code:
Yr1 Sales =
CALCULATE(
SUM(Actuals[Lawson SALES]),
DATESINPERIOD (
'Date'[Date],
MIN('STORE DATABASE'[STORE_OPEN_Date]),
12,
MONTH))
My Code for a measure [Yr2 Sales] (error):
**Yr2 Sales =
VAR Yr2StartDate = DATEADD('STORE DATABASE'[STORE_OPEN_Date],12,MONTH)
VAR SalesOfYear2 = CALCULATE(
SUM(Actuals[Lawson SALES]),
DATESINPERIOD (
'Date'[Date],
Yr2StartDate,
12,
MONTH))
RETURN
SalesOfYear2**
error message when I drag the measure to the same table: "MdxScript(Model)(24, 9) Calculation error in measure 'Actuals'[Yr2 Sales]: A table of multiple values was supplied where a single value was expected.
[1]: https://i.stack.imgur.com/XrlrD.png

Calculate Running Average Using DAX in Power BI

I have the following values in Table_1:
date sales_amount
04/01/2021 100.00
04/02/2021 300.00
04/05/2021 500.00
I want to compute a running average, so the average is computed as each day passes, so that my final output looks like this:
date sales_amount running_average
04/01/2021 100.00 100.00
04/02/2021 300.00 200.00
04/05/2021 500.00 300.00
The sales person did not work on 04/03 and 04/04, so I want to exclude them from my running average.
Right now, my output looks like this, which is wrong for what I am doing:
date sales_amount running_average
04/01/2021 100.00 100.00
04/02/2021 300.00 200.00
04/05/2021 500.00 180.00
Any suggestions?
Right now, my DAX code looks like this:
test_new =
VAR LastVisibleDate = MAX('Table_1'[Date])
VAR FirstVisibleDate = MIN('Table_1'[Date])
VAR LastDateWithSales =
CALCULATE(
MAX('Table_1'[Date]),
REMOVEFILTERS()
)
VAR Result =
IF (
FirstVisibleDate <= LastDateWithSales,
CALCULATE(
AVERAGE([Sales_Amount]),
Table_1[Date]
)
)
RETURN
Result
I have added a few lines in the last variable:
Table_1[Date] in the last variable basically means FILTER ( ALL ( Table_1[Date] ), TRUE ), and that will return all of the dates so not useful in your scenario as it will give wrong results, instead write Table_1[Date] <= LastVisibleDate
You don't need REMOVEFILTERS when you have Date column coming from the Dates table and the Date table is marked as a Date table because when a date table is marked as a date table the engine automatically adds a REMOVEFILTERS/ALL whenever a filter is applied over the Date column, but that won't happen with Date column of other tables hence you need to write an explicit REMOVEFILTERS in the last variable
test_new =
VAR LastVisibleDate =
MAX ( 'Table_1'[Date] )
VAR FirstVisibleDate =
MIN ( 'Table_1'[Date] )
VAR LastDateWithSales =
CALCULATE (
MAX ( 'Table_1'[Date] ),
REMOVEFILTERS ()
)
VAR Result =
IF (
FirstVisibleDate <= LastDateWithSales,
CALCULATE (
AVERAGE ( [Sales_Amount] ),
Table_1[Date] <= LastVisibleDate,
REMOVEFILTERS ( Table_1 )
)
)
RETURN
Result
As a best practice always use Date column from a Date table.

Sum row with next row value and grab next value in other column for the date selected

Let's say I have this data:
Earn Earn Cum.
13-Apr - -
14-Apr 48 48
15-Apr 257 305
16-Apr 518 823
17-Apr 489 1,312
18-Apr 837 2,149
19-Apr 1,005 3,154
20-Apr 1,021 4,175
21-Apr 1,463 5,638
22-Apr 2,630 8,268
23-Apr 2,993 11,261
24-Apr 3,354 14,615
25-Apr 4,332 18,947
26-Apr 4,885 23,832
27-Apr 4,514 28,346
28-Apr 4,356 32,702
29-Apr 4,824 37,526
30-Apr 7,082 44,608
1-May 6,091 50,699
2-May 1,407 52,106
When a date is selected in a dropdown slicer for example: 1-May I'd like to sum the rows 1-May with the next row 2-May for the column Earn and grab the next value 52,106 for the column Earn Cum.. The result should be:
1-May 7,498 52,106
Another example: if the date selected was 30-Apr the result must be:
30-Apr 13,173 50,699
I'm scratching my head trying to do this using a measure in Power BI.
I'll call your table "Data".
Create a measure:
Next Earn =
VAR Current_Date = MAX ( Data[Date] )
VAR Next_Date = Current_Date + 1
RETURN
CALCULATE (
SUM ( Data[Earn] ),
Data[Date] = Current_Date || Data[Date] = Next_Date
)
Create another measure:
Next Cum Earn =
VAR Current_Date = MAX ( Data[Date] )
VAR Next_Date = Current_Date + 1
RETURN
CALCULATE ( SUM ( Data[Earn Cum] ), Data[Date] = Next_Date )
Result:
Note: the code assumes that your dates are sequential (no gaps). If they have gaps, things are a bit more complex.
It will help to have access to date intelligence, so create a date table if you don't have one already. The following dax sets up a small table that just barely covers the sample data in your example.
Date = CALENDAR(Date(2019,4,10),Date(2019,5,5))
Create a relationship between the Dates in your table and the new Date dimension. Add a slicer to your visuals using the Date dimension.
We can use IF and ISFILTERED to check if filtering is being done. If we aren't filtering on Date then we get the normal table behavior. If we are, we'll see our modified result.
Earn _ Alt =
var tomorrow = CALCULATE (
SUM(Table1[Earn]),
dateadd('Table1'[Date], 1, DAY)
)
return Sum(Table1[Earn]) + IF(ISFILTERED`('Date'[Date]),tomorrow,0)`
and
Earn Cum. _ Alt = IF(ISFILTERED('Date'[Date]),
CALCULATE (
SUM(Table1[Earn Cum.]),
dateadd('Table1'[Date], 1, DAY)
),
SUM(Table1[Earn Cum.]))
Results:
-Unfiltered-
-Filtered-