Value of the first order of every customer - powerbi

I'm working on a school assignment where I have to look at the value of every first voucher value of a customer. Now I am working on it and I did manage to get the first date of each customer. However, when I put the value in the table it always takes the total sometimes of this customer ID so that some lines score considerably higher
Code
First transaction date =
MINX(FILTER('Tekst','Tekst'[PCHN]='Tekst'[PCHN]),'Tekst'[Datum].[Date])
enter image description here

Try making your first transaction date into a column:
First_transaction_date = CALCULATE(
MIN('Table'[date]),
FILTER(
'Table',
'Table'[customer]=EARLIER('Table'[customer])
)
)
Then calculate the corresponding value. I used SUM, so if multiple values are on the same date, it will sum them. If you want the min/max/mean of these values when multiple occur, that's up to you:
first_voucher_value = CALCULATE(
SUM('Table'[value]),
'Table'[First_transaction_date] == 'Table'[date])
I believe in your example:
Table => Tekst,
date = Date,
customer = PCHN,
value should be your 'voucher value column'.

Related

How to produce a snapshot table using Power BI measure

My intention is to populate days of the month to simulate a data warehouse periodic snapshot table using DAX measures. My goal is to show non-additive values for the quantity.
Consider the following transactions:
The granularity of my snapshot table is day. So it should show the following:
Take note that a day may have multiple entries but I am only interested in the latest entry for the day. If I am looking at the figures using a week period it should show the latest entry for the week. It all depends on the context fixter.
However after applying the measure I end up with:
There are three transactions. Two on day 2 and the other on day 4. Instead of calculating a running total I want to show the latest Qty for the days which have no transactions without running accumulating totals. So, day 4 should show 4 instead of summing up day 3 and day 4 which gives me 10. I've been experimenting with LASTNONBLANK without much success.
This is the measure I'm using:
Snapshot =
CALCULATE(
SUM('Inventory'[Quantity]),
FILTER(
ALL ( 'Date'[Date] ),
'Date'[Date] <= MAX( 'Date'[Date] )
)
)
There are two tables involved:
Table # 1: Inventory table containing the transactions. It includes the product id, the date/time the transaction was recorded and the quantity.
Table # 2: A date table 'Date' which has been marked as a date table in Power BI. There is a relationship between the Inventory and the Date table based on a date key. So, in the measure, 'Date'[Date] refers to the Date column in the Date table.
You can use the LASTNONBLANKVALUE function, that returns the last value of the expression specified as second parameter sorted by the column specified as first parameter.
Since LASTNONBLANKVALUE implicitly wraps the second parameter into a CALCULATE, a context transition happens and therefore the row context is transformed into the corresponding filter context. So we also need to use VALUES to apply the filter context to the T[Qty] column. The returned table is a single row column and DAX can automatically convert a single column, single row table to a scalar value.
Then, since we don't have a dimension table we have to get rid of cross-filtering, therefore we must use REMOVEFILTERS over the whole table.
the filter expression T[Day] < MaxDay is needed because LASTNONBLANKVALUE must be called in a filter context containing all the rows preceding and including the current one.
So, assuming that the table name is T with fields Day and Qty like in your sample data, this code should work
Edit: changed in order to support multiple rows with same day, assuming the desired result is the sum of the last day quantities
Measure =
VAR MaxDay =
MAX ( T[Day] )
RETURN
CALCULATE (
LASTNONBLANKVALUE (
T[Day],
SUM ( T[Qty] )
),
T[Day] <= MaxDay,
REMOVEFILTERS ( T )
) + 0
Edit: after reading the comments, this might work on your model (untested)
Measure =
VAR MaxDay =
MAX ( 'Date'[Date] )
RETURN
CALCULATE (
LASTNONBLANKVALUE (
Inventory[RecordedDate],
SUM ( Inventory[Quantity] )
),
'Date'[Date] <= MaxDay
) + 0

Power BI counting double values

I'm trying to create a measure in Power BI that will count doubles as a single value and then later add them all up to see how many doubles we have. Here is an example:
Each customer whose name shows up more than once should be counted as 1
Bonus question, how can I make a measure which will count customers whose name only shows up once (example name - Sarah).
Thanks in advance!
If you want to count the customers distinct you can use:
CountCustomers = DISTINCTCOUNT([Customer])
if you want to count the doubles, you can use:
Doubles = COUNTROWS(FILTER(SUMMARIZE(CusTable, CusTable[Customer], "countC", COUNTROWS(CusTable)), [countCol] > 1))
First I summarize it to a table with the name of the customer and how often it is appearing in the table
Next I filter this table by all rows bigger than 1
Last I count the rows
You can create this below measure to check the customer is there for once or multiple time in the list. This measure will return 1 if the customer is there for once and 0 if the customer exists for multiple time.
is_unique =
VAR current_customer = MIN(your_table_name[customer])
VAR customer_count =
CALCULATE(
COUNT(your_table_name[customer]),
FILTER(
ALL(your_table_name),
your_table_name[customer] = current_customer
)
)
RETURN IF(customer_count = 1, 1, 0)
This will return 1 for customer- Sarah and David. For all other customer, it will return 0. Now, if you add the above measure to a Card and apply SUM on the measure, it will return value 2 which is basically your customer count with single existence.

Daily hospital census: Summarize a table filtered for each date

I'm trying to count how many patients were in the hospital from one day to another and in which clinical department and specialty.
There is one table 'Patient Flow' with all patient's path during his hospitalization.
I was able to calculate this measure with another table 'Patient Entry-Out Date', where I filtered (ENTRY DATES < DATE REFERENCE) and (OUT DATES >= DATE REFERENCE or OUT DATES = null).
However, this way I can't identify what was the correct clinical department and specialty of this patient.
For example: the patient
03/13/2019 - shouldn't be counted
03/14/2019 - should be counted in clinical: UNIDADE CORONARIANA and specialty: CARDIOLOGIA
03/15/2019 - should be counted in clinical: UNIDADE CORONARIANA and specialty: CARDIOLOGIA
03/16/2019 - should be counted in clinical: CIRÚRGICA III and specialty: CARDIOLOGIA
03/17/2019 - should be counted in clinical: CIRÚRGICA III and specialty: CARDIOLOGIA
03/18/2019 - shouldn't be counted
I tried to create an index and get the maximum value between Admissions and Entry Transfer (table Last entry), but couldn't do it for each day.
Is it possible to do a summary in a filtered table(admissions and entries before) for each reference date ?
Or another solution?
Thanks in advance!
Pbix file https://www.dropbox.com/s/bqhyj4gihb5g4la/Daily%20hospital%20census.pbix?dl=0
Cássio A. Andrade 
Here is a solution I was able to create. (working pbix can be downloaded from here)
1. Transformation
I used PowerQuery to transform original "Patient Flow" table into a new table (named "Patient Attendance") like below.
In this transformed table, each row represents a patient's attendance with a clinical department. A patient may enter a clinical department for an occurrence of either "Admission" or "Enter transfer", and may exit the department for either "Output transfer", "Medical release", or "Death". Each row has two time stamps; when the patient entered and exited the department.
Note, patients may be still staying with the department at the time when data is collected. In this case, exit time stamp for that patient is blank.
2. Modeling
I created a data model, which is a star schema composed of one fact table PatientAttendance illustrated above, and 3 dimension tables Clinics, Specialties, and Patients. Additionally, we have the Calendar dimension table, which does not have any physical relationship to other tables, but is used for measure calculation and slicing.
Then, I created the measure on top of this model which calculate how many patients were staying with the clinical department on any given day or period. The basic concept of the calculation logic is,
Look at each individual patient.
Look at each calendar date.
If the patient is staying with any department on the given day, add 1 count.
Patient-Days Stayed =
SUMX(
'Patients',
SUMX(
'Calendar',
IF(
CALCULATE(
COUNTROWS(
FILTER(
'PatientAttendance',
VAR CurrentDate = VALUES( 'Calendar'[Date] )
RETURN
'PatientAttendance'[Enter Timestamp].[Date] <= CurrentDate
&& (
ISBLANK( 'PatientAttendance'[Exit Timestamp] )
|| (
NOT( ISBLANK( 'PatientAttendance'[Exit Timestamp] ) )
&& 'PatientAttendance'[Exit Timestamp].[Date] > CurrentDate
)
)
)
)
) > 0, 1
)
)
)
The result looks to be working correctly (ignore too small numbers in early January, this is due to the sampling method of source data). If I am making any error, or if there is any suggestion of better approach, I am very interested to hear.

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date

Including groups with no values in stacked column chart

I'm building a chart that will cumulatively sum Invoice Values for the next month, broken out by category of sale. It looks like this:
My problem is that for particular slicer values, there might not be any invoices for a particular category, and thus the groups just don't show in the graph:
This looks scrappy, so I'm trying to force them to show. Given the rows simply don't exist the way I'm trying to do this is to have a new table which has a row per-date-per-category, and use a measure to cumulatively sum all the data from my source table. So for example given this source table:
I've built the structure of this table, but I need to find a way to add the "Cumulative Value" field that's also shown:
Unfortunately I can't work out how to make that work. The usual cumulative sum syntax would be:
Cumulative Value = (
CALCULATE(
SUM('Table 1'[Value]),
FILTER(ALLSELECTED('Table 1'), ISONORAFTER('Table 1'[Date], MAX('Table 1'[Date]), DESC))
)
)
And I can't seem to add in another filter expression without either
Breaking it such that it returns different values per category but the same value for every date
Breaking it such that it returns different values per date but the same value for each category
So; what Measure can I build to create that "Cumulative Value" field?
Never mind, I got it. Full DAX for the answer was:
CumulativeValue =
VAR CurrActionDate = MAX('Table 2'[Date])
VAR CurrTransType = MAX('Table 2'[Category])
RETURN (
CALCULATE(
SUM('Table 1'[Value],
FILTER(
ALLSELECTED('Table 1'),
'Table 1'[Date] <= CurrActionDate
),
FILTER(
ALLSELECTED('Table 1'),
'Table 1'[Category] = CurrTransType
)
)
)
Ta-da! Cumulative sum across different groups with no blank values.