Sample table:
N ProductName Cost Type TOTAL
1 ProductX 3 Checker
2 Product0 5 TOY
3 Product1 5 TOY
4 Product2 8 TOY
Rows 2,3,4 Need Cost Of Type = Checker + current row cost into the TOTAL column. So row 2 would be 8, 3 would be 8 and 4 would be 11
5 ProductZ 10 Checker
6 Product3 5 TOY
7 Product4 9 TOY
8 Product5 18 TOY
9 Product6 25 TOY
Likewise, these need Cost of ProductZ added to their totals. So Row 6 would be 15, 7 would be 19, and so on. They cannot go back and reference ProductY at row 1.
The datasets are not always the same, and there may be more “Checker” type items in the dataset.
When there’s only one, it works really well, obviously. But when there’s more than one I have issues where the products total is wrong because it’s using the wrong “Checker” value.
I think this query works.
The first CTE, “toysAndCheckers”, gets for each toy the N of the CHECKER row that is highest while still being lower than the TOY in question. The second one just replaces the N of the checker with the cheker’s cost. Then you have a straightforward merge. Assuming the N column is unique, you’ll never have multiple matches.