We have a table for our stored-value cards:
CardNo TransactionType Amount TransactionDate(datetime2)
(1 for Top-up, 0 for purchasing products)
=========================================================
0001 1 1000.00 20170809(only date is displayed for brevity)
0001 0 200.00 20170810
0001 0 300.00 20170811
0001 1 200.00 20170811
0001 0 200.00 20170812
We would like to know for each card (customer), the time between each purchase and the most recent top-up at that time. So the intended result is:
RowID GapDays
================
1 Null (or 0)
2 1
3 2
4 Null
5 1
Why is there a gap of 2 days for a row id of 3?
The purchase happens before the top-up.
The date column is of type datetime2
, has a "time" portion (omitted here for brevity), and the data is ordered by that. You may utilize any index. Non-existent index will be added if necessary.
Best Answer
I've added time part to the
TransactionDate
just to get the correct order for the transactions:Then you can get it by using an
APPLY
operator with all records whereTransactionType = 1
. Note you must limit to one record the rows returned by the subquery.dbfiddle here