I have a result-set below
Rank cardID DespatchValue Spend SumSpend Spendtype
0 468612 500 0 0 Despatch
1 468612 500 -8500 -8500 Topup
2 468612 500 -11500 -20000 Topup
3 468612 500 -3500 -23500 Topup
As you can see each spend is added to the Sum spend (via a recursive CTE) which i am happy with.
However the logic needs to work thus
- Despatch value up to initial spend = Spend type Balance
- Anything after that = Top up
So,
I would like to see :
Rank cardID DespatchValue Spend SumSpend Spendtype
0 468612 500 0 0 Despatch
? 468612 500 -500 -500 Balance
1 468612 500 -8000 -8500 Topup
2 468612 500 -11500 -20000 Topup
3 468612 500 -3500 -23500 Topup
Any ideas on how to achieve this?
To do a split row, you’ll need to add two more UNION clauses to your CTE. Most recursive CTE’s have an “anchor” and a recursive bit. You’ll need to expand how that recursive bit works. First, you identify when to surpress the “nominal” case, which for you is when the balance transitions from a positive total to negative. In your case that’s “DespatchValue + SumSpend”.
The next two terms will be your “split” rows. Using the inverse of whatever condition is above (ie, only bring back the rows over this “special” condition). The first UNION will be be the “BALANCE” record, taking it down to 0. The second is the remainder of what’s left over.
Here’s what I came up with – note that I added a “subid” column to indicate the “balance” (and to prevent duplicates in the later-on recursion). I also added a “DespatchBalance”, assuming that’s really what you’re checking against. Specifics aside, the general format should be good: