I use SQL Server 2012 and I have these tables:
Table Tb1 (ID Int, CodeID Int, Value Int
)
ID CodeID Value
----------------------
1 1 10
2 1 14
3 1 5
4 1 25
5 2 12
6 2 17
7 2 4
8 2 10
9 2 6
Table Tb2 (CodeID Int Value Int
)
CodeID Value
---------------
1 25
2 20
I want a query for get records from Tb1 that SUM(Tb1.Value) <= Tb2.Value
For example result for above records is :
Tb1.ID Tb1.CodeID Tb1.Value UsedValue Tb2.Value
--------------------------------------------------------
1 1 10 10 25
2 1 14 14 25
3 1 5 1 25
5 2 12 12 20
6 2 17 8 20
I use cursor for get above query. But my query, execute with low performance. I want a query without cursor.
EDIT 1 UsedValue is Tb1.Value until sum of Tb1.Value was lowest than Tb2.Value.
Try this:
See result on SQL FIDDLE
there is only one assumption when i wrote this code . that rows are ordered by ID, if it is not true you have to add ordering column !