Get Value from Min and Max date in Power Bi - Group by - powerbi

I am working with a database of surgeries performed.
The database contains in each row the patient's id, date of surgery and surgery performed.
A patient can have more than one surgery and this surgery can be different.
What I am trying to obtain is the number of surgeries performed by each patient, what was the first surgery and the last surgery performed.
This is the original database example:
patient
date
surgery
id
A
01-01-22
Eyes
1
B
01-01-22
Mouth
2
C
01-01-22
Nose
3
A
01-05-22
Mouth
4
C
01-06-22
Eyes
5
B
01-07-22
Mouth
6
A
01-12-22
Nose
7
I need the following output:
patient
number of surgeries
First Surgery
Last Surgery
A
3
Eyes
Nose
B
2
Mouth
Mouth
C
2
Nose
Eyes
I'm using the following Dax's expression:
N_Surgery = GROUPBY(Surgery, Surgery[patient_id],
"N_Surgery", COUNTX(CURRENTGROUP(), Surgery[id]))
But i have no idea how to get the last and first surgery.
This is what I am looking to replicate using an example of R code:
Summarise <- DF%>%
group_by(patient_id)%>%
summarise(N_Surgery = n(),
First = surgery[which.min(date)],
Last = surgery[which.max(date)])
Thanks in advance!

Table:
Code:
Table 2 =
ADDCOLUMNS(
SUMMARIZE('Table', 'Table'[patient]),
"Number of Surgeries", CALCULATE(COUNTROWS('Table')),
"First Surgery",
VAR a = CALCULATE(MIN('Table'[date]))
RETURN CALCULATE(MIN('Table'[surgery]), 'Table'[date] = a),
"Last Surgery",
VAR b = CALCULATE(MAX('Table'[date]))
RETURN CALCULATE(MIN('Table'[surgery]), 'Table'[date] = b)
)

You can also try with this 3 measure-
surgery_count = count('your_table_name'[patient])
surgery_first =
var current_patient_min_date =
CALCULATE(
MIN('your_table_name'[date]),
ALLEXCEPT('your_table_name','your_table_name'[patient])
)
RETURN
CALCULATE(
MIN('your_table_name'[surgery]),
FILTER(
ALLEXCEPT('your_table_name','your_table_name'[patient]),
'your_table_name'[date] = current_patient_min_date
)
)
surgery_last =
var current_patient_max_date =
CALCULATE(
MAX('your_table_name'[date]),
ALLEXCEPT('your_table_name','your_table_name'[patient])
)
RETURN
CALCULATE(
MIN('your_table_name'[surgery]),
FILTER(
ALLEXCEPT('your_table_name','your_table_name'[patient]),
'your_table_name'[date] = current_patient_max_date
)
)
Output-

Related

How to create a measure that sums rows only where sales exists this and last year?

Hello community and DAX gurus!
I am trying to create a measure that calculates the total product sales for a specfic month only for does products that has been sold the same period last year.
Below is an illustration of what I want to achieve:
The first thing I did was to create a measure to calculate the Sales Amount for previous year:
Sales Amount PY =
CALCULATE(
[Sales Amount],
SAMEPERIODLASTYEAR(DimDate[Datekey])
)
The second thing I did was to create a Comparable range flag as measure:
ComparableRange = IF(FactSales[Sales Amount] = BLANK() || FactSales[Sales Amount PY] = BLANK(),0,1)
Third step I created a measure to calculate the total product sales:
Total Product Sales =
CALCULATE(
FactSales[Sales Amount],ALL(DimProduct)
)
The final step I want to calculate the total product sales only for does products being comparable.
I tried this solution but not getting it to work, it is only returning blank:
Total Product Sales Comparable =
var CompRangeTable = ADDCOLUMNS(FactSales,"#CompRange",[ComparableRange])
var FilteredTable = FILTER(CompRangeTable,[#CompRange] = 1)
return
CALCULATE(FactSales[Sales Amount],ALL(DimProduct),FilteredTable)
I also tried this solution but still getting blanks:
Total Product Sales Comparable =
var FilteredTable = FILTER(FactSales, [Sales Amount PY]*[Sales Amount]+0<>0)
return
CALCULATE([Sales Amount],ALL(DimProduct),FilteredTable)
I wonder if the issue is that the Comparable range flag doesn't evaluate during context in the measure and potentially only returning 0 and if that is the case how would you go about to solve this problem.
To demonstrate my problem I have used the ContosoRetailDW sample database with a simple star scheme consisting in the tables "FactSales", "DimDate" and "DimProduct"
This expression
ADDCOLUMNS(FactSales,"#CompRange",[ComparableRange])
is equal to
CALCULATETABLE(
ADDCOLUMNS(FactSales,"#CompRange",[ComparableRange])
,Calendar[CalendarMonth]=2000805
,DimProduct[Brand]="The Phone Company"
)
so :
1 - FactSales is cutted by context
2 - ADDCOLUMNS applies a row context to [ComparableRange] measure
to EACH row.
For example you have a row with FactSales[date]="01/01/2022"; FactSales[product]="iPhone"; FactSales[customer]="Bill Gates" ; FactSales[price]=200 ; FactSales[qty]=10 Your [Sales Amount PY] in [ComparableRange] will search SAMEPERIODLASTYEAR() on a day level, for the sample it is - "01/01/2021" most probably you have no sales for customer "Bill Gates" that date, so [ComparableRange] will return you - 0
Try this one, it's not optimized, so just check if it works.
Total Product Sales Comparable=
VAR CurrentCalendarMonth = SELECTEDVALUE(Calendar[CalendarMonth])
VAR allProducts =
CALCULATETABLE(
VALUES(DimProduct[ProductName])
,ALL() -- remove all filters and crossffilters from your data model
)
VAR totalSalesAndCompRng =
ADDCOLUMNS(
allProducts
,"#totalAmount
,CALCULATE(
[Sales Amount]
,Calendar[CalendarMonth] = CurrentCalendarMonth
)
,"#CompRange"
,CALCULATE(
[ComparableRange]
,Calendar[CalendarMonth] = CurrentCalendarMonth
)
)
VAR onlyCompRng =
FILTER(
totalSalesAndCompRng
,[#CompRange]=1
)
RETURN
SUMX(onlyCompRng,[#CompRange])
Your second measure:
Total Product Sales Comparable =
var FilteredTable =
FILTER(
FactSales
,[Sales Amount PY]*[Sales Amount]+0<>0 -- returns false
-- the reason is the same
-- as above
-- and FilteredTable is empty
)
RETURN
CALCULATE(
[Sales Amount]
,ALL(DimProduct)
,FilteredTable
)
You can try smth like this:
Total Product Sales Comparable =
var FilteredTable =
FILTER(
All(DimProduct)
,NOT [Sales Amount PY]*[Sales Amount]=0
)
VAR CurrentCalendarMonth = SELECTEDVALUE(Calendar[CalendarMonth])
RETURN
SUMX(
FilteredTable
,CALCULATE(
[Sales Amount]
,Calendar[CalendarMonth]=CurrentCalendarMonth
)
)

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

Need to Filter a Table Based on Top N from Another Table

I'm trying to return values for only the top 4 countries
Top 4 Fully Vaccinated 3 =
VAR _Countries = TOPN(4,VALUES(DimCountries[Country]),[Fully Vaccinated %],DESC)
RETURN
CALCULATE(
[Fully Vaccinated %],
FILTER (
ALL(DimCountries),DimCountries[Country] IN _Countries
)
)
However, I still get all rows with a value
Fully Vaccinated % =
DIVIDE(
SUMX(
GROUPBY(FactCovid19,DimCountries[CountryKey],"Current Fully Vacc",MAXX(CURRENTGROUP(),FactCovid19[FullyVaccinated])),
[Current Fully Vacc]
),
[MTotalPopulation]
)
If I try to hardcode the country names it works fine. I also, tried the TOPN expression as a new table and it does return the 4 countries.
Does anyone knows what am I missing?

Cumulative of Cumulative measure power bi

Hi Team,
I need 2 output.
Output1 = Cumulative of No of Item.
Output2 = Cumulative of Output1.
Please help me.
If you have Date column from where you are picking the Month name, you can try this below 2 custom column code. I just considered first date of each month in the date column, but it will work for any date. this below column will give you cumulative vale per Year to Month-
Note- Based on your Date value, you may need some adjustment in the script. But using this logic, you should achieve your required output.
C1 =
var current_row_date_month = your_table_name[Date].[MonthNo]
return
CALCULATE(
SUM(your_table_name[No Of Item]),
FILTER(
ALLEXCEPT(your_table_name,your_table_name[Date].[Year]),
your_table_name[Date].[MonthNo] <= current_row_date_month
)
)
C2 =
var current_row_date_month = your_table_name[Date].[MonthNo]
return
CALCULATE(
SUM(your_table_name[C1]),
FILTER(
ALLEXCEPT(your_table_name,your_table_name[Date].[Year]),
your_table_name[Date].[MonthNo] <= current_row_date_month
)
)
Here is the sample output-

QoQ changes by Customer in DAX

I would like to create a DAX formula to calculate the increases and decreases of customers across periods. Following is a sample of the data that I have
Year-Quarter|Customer|Credit-Limit
2019Q2|A|50
2019Q2|B|100
2019Q2|C|100
2019Q2|D|200
2019Q2|E|1000
2019Q2|F|200
2019Q3|A|50
2019Q3|B|200
2019Q3|C|100
2019Q3|D|50
2019Q3|E|500
2019Q3|F|300
I am looking to create a summary by Year-Quarter showing the number of customers that had an increase/decrease/none of their Credit-Limit.
Note that this is just a sample and the actual data is >10M rows. So even though I can create another table, I think from a computation standpoint, a measure would be more useful
Desired Output:
A commentary like the following: "There are 2 customers that have increased credit limit in 2019Q3"
Done so far:
Prev Quarter Credit Limit =
VAR CurrentYearQuarter = MAX(Sheet1[Year-Quarter])
VAR Quarter_Year =
LEFT (CurrentYearQuarter, 4)
VAR Quarter_period =
RIGHT (CurrentYearQuarter, 1 )
RETURN
IF (
Quarter_period = "1",
CALCULATE (
SUM ( Sheet1[Credit Limit] ),
Sheet1[Year-Quarter]
= ( Quarter_Year - 1 )
& "Q"
& ( Quarter_period + 3 )
),
CALCULATE (
SUM ( Sheet1[Credit Limit] ),
Sheet1[Year-Quarter]
= Quarter_Year
& "Q"
& Quarter_period - 1
)
)
Inc/Dec = IF(SUM(Sheet1[Credit Limit]) - [Prev Quarter Credit Limit] > 0,"Inc",
IF(SUM(Sheet1[Credit Limit]) - [Prev Quarter Credit Limit] < 0,"Dec","None"))
Commentary = "There are " &
CALCULATE(DISTINCTCOUNT(Sheet1[Customer]),
FILTER(Sheet1, [Inc/Dec] = "Inc" && Sheet1[Year-Quarter] = "2019Q3"))
Current output:
Commentary: "There are 4"
I am not sure why I am getting 4 as compared to 2 as the number here. Help or guidance would be really appreciated
I've slightly altered the input data for experimental purpose, I've added
2018Q3 | A | 200
2018Q4 | A | 50
2019Q1 | A | 50
I've added a Quarter-Calendar (which is a calculated table using VALUES(Sheet1[Year-Quarter])
Then by adding more columns to this new table, extracting the current year and quarter using LEFT and RIGHT, then calculating the previous quarter, previous year and combining to a Prevoius-Year-Quarter column:
]
Using this Q-Calendar I create a 1:* relationship to the Sheet1 table between [Year-Quarter] and [Year-Quarter], then I create a second inactive 1:* relationship between [Previous-Year-Quarter] and [Year-Quarter] like this:
I then create two measures, one for sum of previous quarter credit an one for current quarter credit:
Current-Quater CL =
var currentQ = MAX('Q-Calendar'[Year-Quarter])
var tempTable =
FILTER(
ALL('Q-Calendar');
'Q-Calendar'[Year-Quarter] = currentQ
)
return
CALCULATE(
SUM('Sheet1'[Credit-Limit ]);
tempTable
)
In the [Previous-Quarter CL] measure I use USERELATIONSHIP to activate the passive relationship I added from the Q-Calendar.
Prev-Quater CL =
var currentQ = MAX('Q-Calendar'[Year-Quarter])
var tempTable =
FILTER(
ALL('Q-Calendar');
'Q-Calendar'[Year-Quarter] = currentQ
)
return
CALCULATE(
SUM('Sheet1'[Credit-Limit ]);
tempTable;
USERELATIONSHIP('Sheet1'[Year-Quarter]; 'Q-Calendar'[Previous-Year-Quarter])
)
Then create the Inc/Dec measure like this:
Increase/Decrease =
var temp = [Current-Quater CL]-[Prev-Quater CL]
return
SWITCH(
TRUE();
temp > 0; "Increase";
temp < 0; "Decrease";
"No change"
)
And finally created a new (actually 3 new) Commentary measures like this:
Commentary_2 = "There are " &
var customers = VALUES(Sheet1[Customer])
return
SUMX(
customers;
CALCULATE(
IF(
[Current-Quater CL]-[Prev-Quater CL] > 0;
1;
0
)
)
)&" customers how have increased their credit"
Using the Year-Quarter column from the Q-calendar as a slicer I get the current status and I can select a previous quarter to see the status at that time:
N.B: The code in my measures can be optimised, I just kept them as detailed as this to make it more understandable.