I have a table with next structure

```
Id|State|Quan|SellQuan|LastId
3 |2    | 5  | 0      |2
2 |3    |10  | 5      |1
1 |3    |15  | 5      |NULL

```

LastId is referenced on Id field, I need calulate value on next step: take Quan from Id=3 then add all sellquan with Id referenced on previous LastId. thats meen 
Id=3 - lastId = 2 => take value from Id=2 field sellquan then chek if lastId is not null
.In my ecample LastId = 1 => Take Id=1 value SellQaun
Result: 5 + 5+ 5 = 15