QoQ changes by Customer in DAX - powerbi

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.

Related

PowerBi Circular Dependancy issue

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.

How to create a DAX calculated column in PowerBi that finds the MIN value based on another columns FIRSTDATE?

Need some help to calculate the following in two separate columns in a DAX formula
Earliest Reading for each equip
Latest Reading for each equip
Screenshot of sheet
I've been able to get the first date of each equip with this.
CALCULATE(FIRSTDATE(Transactions[Date]),ALLEXCEPT(Transactions,Transactions[Equip No]))
But cannot work out how to get the 'Reading' value that is associated with the first date
I've managed to do this with a measure, but would also like to get this in a calc. column.
Latest Reading =
SUMX (
VALUES( Transactions[Equip No] ),
CALCULATE ( MIN ( Transactions[Reading] ), FIRSTDATE ( Transactions[Date] ) )
)
this should help you.
Earliest Column
Earliest =
VAR __equipNumber = 'Transaction'[Equip No] //Get the Equip No to filter the main table and create an auxiliar table for every different Equip No.
VAR __minDate = CALCULATE( MIN('Transaction'[Date]), FILTER( 'Transaction', 'Transaction'[Equip No] = __equipNumber ) ) //Get the lowest date asociated to every Equip No.
VAR __subTable = FILTER( 'Transaction', 'Transaction'[Date] = __minDate ) //Create a table that contains 1 row asociate to the lowest date.
Return CALCULATE(SUM('Transaction'[Reading]), __subTable) //Operate over the auxiliar table to get the expected value.
Latest Column
Latest =
VAR __equipNumber = 'Transaction'[Equip No]
VAR __maxDate = CALCULATE( MAX('Transaction'[Date]), FILTER( 'Transaction', 'Transaction'[Equip No] = __equipNumber ) )
VAR __subTable = FILTER( 'Transaction', 'Transaction'[Date] = __maxDate )
Return CALCULATE(SUM('Transaction'[Reading]), __subTable)
I obtained the expected result

Sum of the total count (Running total based on User Count) - Is it possible?

I am trying to do the cumulative count for the users first time access the web page.
Table looks like,
UserID , Initial Access Date
100, 2019-05-10
200, 2019-05-20
100, 2019-05-21
100, 2019-05-25
200, 2019-05-30
300, 2019-06-01
Current Expression:
Cumulative Total =
CALCULATE (
DISTINCTCOUNT ( [USERID] ),
FILTER (
ALLSELECTED ( TABLE ),
[INITIAL ACCESS DATE] <= MAX ( [INITIAL ACCESS DATE] )
)
)
This only returns cumulative total count, How would I get the running total based on this count of Users.
Expected Results:
1 - Upload your Fact table in Power Bi
2 - Create a Date Table
Date = CALENDARAUTO()
Then
Year = Year('Date'[Date])
Month = MONTH('Date'[Date])
YEAR_MONTH = VALUE('Date'[Year])*100+VALUE('Date'[Month])
3 - Set relationships
4 - You can compute a set of two measures :
First
InitialAccess =
VAR InitialAccessInCurrentPeriod =
DISTINCTCOUNT(Fact_T[UserID ])
RETURN
InitialAccessInCurrentPeriod
Then :
InitialAccessCumulated =
VAR MaxDateInPeriod = MAX('Date'[Date]) // Retrieve the last date in current filter context
VAR StartingDate = MINX(ALLSELECTED('Date');[Year]) // Retrieve the lowest year selected on slicer
RETURN
CALCULATE(
[InitialAccess]; // Compute the number of initial access
FILTER( // In a nex filter context where all the dates
ALL('Date'); // Equal or superior to the lowest date selected
'Date'[Year]>=StartingDate
&&
'Date'[Date]<= MaxDateInPeriod // Until the last date visible in the current row context
)
)
You can see the final result here :
I have added to row to your fact table to have several years
Here is the Fact table used :
UserID Initial Access Date
50 12/12/2018
100 10/05/2019
200 20/05/2019
100 21/05/2019
100 25/05/2019
200 30/05/2019
300 01/06/2019
400 04/02/2020
Finally I got it working without creating extra columns or measures,
Cumulative Total =
CALCULATE (
SUMX (
Table,
IF ( DISTINCTCOUNT ( Table[UserID] ) > 0, 1, 0 )
),
FILTER (
ALLSELECTED ( Table ),
Table[InitialAccessDate]
<= MAX ( Table[InitialAccessDate] )
)
)
Cheers!!

How to find DateDiff from same column with condition in Power BI

I am having one table in PowerBI which is having 3 columns: 1.EnrollId 2.Status 3.StatusChangeDate. One EnrollId is having 4 statuses and their particular statusChangeDates. I want to find no. of days between two dates with status condition.
EnrollId Status StatusChangeDate
101 AppStart 15/02/2019
101 Application 27/03/2019
101 Enrollment 03/04/2019
101 Complete 28/04/2019
I want to create formula in DAX like
[StatusChangeDate (where Status="Enrollment") - StatusChangeDate(where status="AppStart)]
or
[StatusChangeDate (where Status="Complete")- StatusChangeDate(where status="Enrollment)]
i.e. 03/04/2019 - 15/02/2019 = 44 Days
28/04/2019 - 03/04/2019 = 25 Days
My advice is go for a Calculated Column, you can try and adjust this to a measure but there is more factors to consider regarding the filter context.
For a calculated column:
DaysLastChange =
VAR _currentStatusChangeDate = [StatusChangeDate]
VAR _currentEnrollId = [EnrollId]
RETURN
DATEDIFF(
CALCULATE(MAX('Table1'[StatusChangeDate]);FILTER('Table1';_currentEnrollId = [EnrollId] && _currentStatusChangeDate > [StatusChangeDate] ));
_currentStatusChangeDate;
DAY
)
If you want measures, try something like this. For each period between two Statuses, you need to create another measure. When more than one [EnrollId] is selected, the measure returns a blank.
Days Enrollment - Complete =
VAR scDateEnrollment =
CALCULATE ( MAX ( 'Table'[StatusChangeDate] ), 'Table'[Status] = "Enrollment" )
VAR scDateComplete =
CALCULATE ( MAX ( 'Table'[StatusChangeDate] ), 'Table'[Status] = "Complete" )
RETURN
IF (
HASONEVALUE ( 'Table'[EnrollId] ),
DATEDIFF ( scDateEnrollment, scDateComplete, DAY )
)
Cardvisuals or a table-visual would look like this. As you can see the table-visual is not affected by the slicer.
EDIT
This is the table i used:

Project revenue calculation in DAX

I need to calculate the ongoing revenue for installation + maintenance for projects and calculate the monthly revenue for controlling purposes in DAX in Power BI.
The problem is the following.
The projects are stored in a table CONTRACTS like this:
And I have a separate date table INST_DATE_TABLE:
The tables are connected via the [INSTALLATION_DATE] field.
For every month the revenue is the total of the [INSTALLATION_REVENUE] if the installation was carried out that month plus from the first month on the monthly maintenance revenue which is given as the [MAINTENANCE_COST_PER_UNIT] * [MAINTENANCE_UNIT] / 12.
And the maintenance revenue should be only calculated if the current date is beyond the installation date!
Some contracts are not yet signed, so they dont't have an installation date set (NULL)
So the INSTALLATION REVENUE DAX is like this:
.INSTALLATION_REVENUE =
CALCULATE (
SUMX(CONTRACTS;
CONTRACTS[INSTALLATION_REVENUE]
);
CONTRACTS[INSTALLATION_DATE] > 0
)
And the MONTHLY REGULAR REVENUE is like this:
.REGULAR_REVENUE =
CALCULATE (
SUMX(CONTRACTS;
CONTRACTS[MAINTENANCE_COST_PER_UNIT]*CONTRACTS[MAINTENANCE_UNIT]
) / 12;
CONTRACTS[INSTALLATION_DATE] > 0
)
For all dates I can calculate the cash flow of the latter like this:
.REGULAR_REVENUE_ONGOING =
CALCULATE (
[.REGULAR_REVENUE];
ALL(INST_DATE_TABLE[INSTALLATION_DATE])
)
which gives me a nice series of monthly revenues for all periods. But I only would like to see this for the periods that are beyond the installation date!
So lets say filtered on contract 1 I have now the following cash flow:
But for periods before 2019.04.01 I would like to see zeros!
How can I do that?
I just can't filter on dates referring to the installation date of the project!
After I have the expected result for one contract it would be easy to sum it up for all contracts like this
.TOTAL_REVENUE =
[.INSTALLATION_REVENUE] + [.REGULAR_REVENUE_EXPECTED]
UPDATE:
I created a cumulative total to display the ongoing revenue as such:
.REGULAR_REVENUE_ONGOING =
CALCULATE (
[.REGULAR_REVENUE];
FILTER(
ALL(INST_DATE_TABLE[INSTALLATION_DATE]);
INST_DATE_TABLE[INSTALLATION_DATE
<=MAX(INST_DATE_TABLE[INSTALLATION_DATE])
)
)
this displays the correct series, but now I have another problem. When I try to cumulate this already cumulative data series it does not add up as a cumulative data series!
Any help would be appreciated
.REVENUE_TOTAL_CUMULATIVE =
CALCULATE(
[.REVENUE_TOTAL];
FILTER(
INST_DATE_TABLE;
INST_DATE_TABLE[INSTALLATION_DATE] <= MAX(INST_DATE_TABLE[INSTALLATION_DATE])
)
)
Assuming there are no end dates to your ongoing revenue, then try:
.REGULAR_REVENUE_ONGOING =
VAR DateMin =
CALCULATE(
MIN ( CONTRACTS[INSTALLATION_DATE] ),
ALL ( INST_DATE_TABLE )
)
VAR DateMax =
MAX ( INST_DATE_TABLE[INSTALLATION_DATE] )
RETURN
SUMX (
FILTER (
ALL ( INST_DATE_TABLE ),
INST_DATE_TABLE[INSTALLATION_DATE] >= DateMin && INST_DATE_TABLE[INSTALLATION_DATE] <= DateMax
),
[.REGULAR_REVENUE]
)
And for a cumulative total revenue:
.REVENUE_TOTAL_CUMULATIVE =
VAR DateCurrent = MAX ( INST_DATE_TABLE[INSTALLATION_DATE] )
VAR CumulativeInstallationRevenue =
CALCULATE (
[.INSTALLATION_REVENUE],
FILTER (
ALL ( INST_DATE_TABLE ),
INST_DATE_TABLE[INSTALLATION_DATE] <= DateCurrent
)
)
VAR CumulativeOngoingRevenue =
SUMX (
FILTER (
ALL ( INST_DATE_TABLE ),
INST_DATE_TABLE[INSTALLATION_DATE] <= DateCurrent
),
[.REGULAR_REVENUE_ONGOING]
)
RETURN
CumulativeInstallationRevenue + CumulativeOngoingRevenue
See https://pwrbi.com/so_55808659/ for worked example PBIX file