Days between a customer’s first and last order with DATEDIFF
Measure customer lifespan in days with DATEDIFF, using MINX and MAXX with RELATED to find each customer’s first and last order dates.
You will learn to
- Count days between two dates with DATEDIFF
- Find first and last order dates through the fact table
- Explain why the Date table alone can’t answer per-customer questions
How it works
`DATEDIFF(start, end, interval)` counts how many interval boundaries lie between two dates: `DAY`, `WEEK`, `MONTH`, `QUARTER` or `YEAR`. Between 1 and 31 January it is 30 days. It is negative when the end comes before the start.
For a customer, the two dates are their **first** and **last** order. Those live in the Sales table as `DateKey` numbers like 20250315, and subtracting keys gives nonsense (20250101 − 20241231 is 8,870, not 1). Iterate the customer’s sales and fetch the real date with `RELATED('Date'[Date])`: `MINX(Sales, RELATED('Date'[Date]))` is the first order date and `MAXX` the last.
Why not `MIN('Date'[Date])`? Filters flow from Customer to Sales, but **not on to Date**. In a customer row the Date table is unfiltered, so MIN and MAX return the first and last day of the calendar for everyone.
Practice it hands-on with a real data model and a live report that updates as you type.
Weeks Between Orders = DATEDIFF(MINX(Sales, RELATED('Date'[Date])), MAXX(Sales, RELATED('Date'[Date])), WEEK)