I want to be able to show what % of the students that were registered in the base term (in selected major) were also registered in the comparison term. Base term and comparison term would be selected by user with slicers.
My data is:
StudentID
Term
Major
12345
Fall21
History
12345
Spring22
English
11111
Fall21
History
22222
Spring22
English
33333
Fall21
Accounting
I'd like to show the number of students in the base term with that major and the percentage of those students that were also in the comparison term regardless of major. So, if base=Fall21, comparison=Spring22, and major=history, then 2 students were registered in base term as History and of them, only 1 returned (I don't care about their subsequent major) for a return rate of 50%.
I've tried:
returners =
VAR base=min(baseterm[Term]) #this is a separate table that the slicer selects on# VAR comp=min(compterm[Term]) #this is a seperate table that the other slicer selects on# RETURN CALCULATE (DISTINCTCOUNT (registration[studentid]), FILTER (registration, registration[Term] = base || registration[Term] = comp))
but that just pulls either term. I've also tried... RETURN CALCULATE (DISTINCTCOUNT (registration[studentid]), FILTER (registration, registration[Term] = base && registration[Term] = comp))
but it returns no values. Given that I can't even get the students and term portion to work, I haven't been able to work out how to include the major.
Try the following measure:
=
VAR SelectedBaseTerm =
MIN( baseterm[Term] )
VAR SelectedCompTerm =
MIN( compterm[Term] )
VAR T1 =
SELECTCOLUMNS(
FILTER( registration, registration[Term] = SelectedBaseTerm ),
"ID", registration[StudentID]
)
VAR RegisteredinBaseTerm =
COUNTROWS( T1 )
VAR RegisteredinCompTerm =
COUNTROWS(
FILTER(
ALL( registration ),
registration[Term] = SelectedCompTerm
&& registration[StudentID] IN T1
)
)
RETURN
DIVIDE( RegisteredinCompTerm, RegisteredinBaseTerm )
Related
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
)
)
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?
I have a case where I'm getting a circular dependency.
I'm trying to calculate what stock will arrive to our warehouse by a certain date, but the eta_date is a calculated date column.
The formula reporting the problem is this :
SIT Arriving Soon =
VAR PastDate = Today() - 40
VAR FutureDate = TODAY() + 14
return
CALCULATE(SUMX(OnOrder,OnOrder[Open ASN qty [units]]]), DATESBETWEEN(OnOrder[ETA Date],PastDate, FutureDate)
)
The issue is that the datesbetween function needs a column to refer to, and my column is the calculated column below, which only refers to other columns within the 'onorder' table:
to understand this formula, here is a small key:
InT is a true/false if a quantity is in transit
Open ASN qty = the qty that is in transit
I then look at different vendors and the shipping mode used to add the number of days transport time.
I then do a calculation to add to the transport time to the 'invoiced by supplier' date, and if the vendor is not one of the defined vendors, then we use the default calculated date "OnOrder[Target VSL3 Date]"
ETA Date =
Var InT = if ( OnOrder[Open ASN qty [units]]] <> 0, 1,0)
Var AAVend = if( OnOrder[Vendor] = "451633" ||
OnOrder[Vendor] = "97051583"||
OnOrder[Vendor] = "452825", "AA", "Non-AA")
Var AATransTime = if( AAVend = "AA", IF(OnOrder[Ship Mode] = "Blitz", 5, IF(OnOrder[Ship Mode] = "Air", 14, 42)), 500)
var TransTime = IF(AATransTime > 0, AATransTime, 99999)
RETURN
if ( InT = 1, DATEADD(OnOrder[Ship Date].[Date], TransTime,DAY), OnOrder[Target VSL3 Date]. [Date])
Can anyone help me to get this issue sorted, or advise a way on how I could calculate this?
Thanks very much!
Ditch the DATESBETWEEN and just filter on the date column:
SIT Arriving Soon =
VAR PastDate = Today() - 40
VAR FutureDate = TODAY() + 14
return
CALCULATE(SUM(OnOrder[Open ASN qty [units]]]), OnOrder[ETA Date] >= PastDate && OnOrder[ETA Date] <=FutureDate)
)
thanks for the reply. I tried the formula, and I still get the circular reference error. It talks about the field 'ADC invoice number'. Here is the code to that :
ADC Invoice No =
CALCULATE ( FIRSTNONBLANK ( 'ADC Movements'[ADC Invoice Number], 1 ), FILTER ( ALL ( 'ADC Movements' ), 'ADC Movements'[PoFull] = OnOrder[PoFull] ) )
I don't see how this conflicts at all.
I am trying to calculate whether a customer that uses a gift card as his first order, will transition into become a "normal" customer, which means that he/she orders without a gift card next time.
I can see from the PaymentMethod how the customer payed (PaymentMethod = "Gift card")
I have made a column that says "Gift card" if the order is purchased with this, otherwise it is blank.
So basically I want to make a column that states: If the customer has their first purchase with a gift card, and makes a new order later, that is not purchased with a gift card.
So for example a 1 if TRUE, a 0 if FALSE.
I have the following columns in my orders table:
OrderID
CustomerID
BookingDate
PaymentMethod (Cash, Credit Card, Gift card etc.)
Gift card (Blank or Gift card)
I have tried different DAX codes, but the thing is - I don't know how I would write that the first order has to be a gift card order, and the next order from the customer has to be a non-gift card order, so I doubt the DAX code that I have tried, would be relevant.
Here is a picture of what I hope to achieve:
I hope someone can lead me in the right direction, thank you in advance.
I'd suggest something along these lines:
TransitioningCustomer =
VAR FirstOrderDate =
CALCULATE ( MIN ( Data[BookingDate] ), ALLEXCEPT ( Data, Data[CustomerID] ) )
VAR FirstOrderGiftCard =
"GC"
IN CALCULATE (
VALUES ( Data[PaymentMethod] ),
ALLEXCEPT ( Data, Data[CustomerID] ),
Data[BookingDate] = FirstOrderDate
)
VAR PaymentMethods =
CALCULATE (
DISTINCTCOUNT ( Data[PaymentMethod] ),
ALLEXCEPT ( Data, Data[CustomerID] )
)
RETURN
IF ( FirstOrderGiftCard && PaymentMethods > 1, 1, BLANK () )
This calculates the first order date and then check whether a gift card was used on that date. It also counts the total number of (distinct) payment methods used.
The conclusion that if a gift card was used on the first date and there was some other type of payment method used as well as some point in the customer's purchase history, then that is a transitioning customer.
With the help of Alexis i ended up with this, that returns a 1 if a customer uses a giftcard for their first order, and something else than giftcard for their second order.
FirstOrderGiftNextOrderNotGift =
VAR FirstOrderID =
CALCULATE (
MIN ( orders[Column1.Order_ID] ),
ALLEXCEPT ( orders, orders[Column1.Customer_ID] )
)
VAR FirstOrderGiftCard =
CALCULATE (
VALUES ( orders[Column1.PaymentMethod] ),
ALLEXCEPT ( orders, orders[Column1.Customer_ID] ),
orders[Column1.Order_ID] = FirstOrderID,
orders[Column1.PaymentMethod] = "Giftcard"
)
VAR PaymentMethods =
CALCULATE (
DISTINCTCOUNT ( orders[Column1.PaymentMethod] ),
ALLEXCEPT ( orders, orders[Column1.Customer_ID] )
)
RETURN
IF (
FirstOrderGiftCard = "Giftcard"
&& orders[ReturningCustomer] = "Yes"
&& PaymentMethods > 1,
1,
0
)
After calculating this column I just created a measure for counting the distinct 1's of the customer numbers.
CountOfCustomersWhoTransitioned =
CALCULATE (
DISTINCTCOUNT ( orders[Column1.Customer_ID] ),
orders[FirstOrderGiftNextOrderNotGift] = 1
)
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.