I have two tables,
Table_A
+---------+----+------------+------------+-----------+
| SurrKey | ID | StartDate | EndDate | Allotment |
+---------+----+------------+------------+-----------+
| 1 | 1 | 2015-01-01 | 2015-01-31 | 1000 |
| 2 | 1 | 2015-01-15 | 2015-02-15 | 1500 |
| 3 | 2 | 2015-01-01 | 2015-01-31 | 1200 |
| 4 | 2 | 2015-02-10 | 2015-03-10 | 1000 |
| 5 | 3 | 2015-01-01 | 2015-01-31 | 1000 |
| 6 | 3 | 2015-01-15 | 2015-02-14 | 1500 |
+---------+----+------------+------------+-----------+
Table_B
+----+------------+------+
| ID | Date | Used |
+----+------------+------+
| 1 | 2015-01-01 | 800 |
| 1 | 2015-01-14 | 300 |
| 1 | 2015-01-15 | 100 |
| 1 | 2015-01-18 | 200 |
| 2 | 2015-01-01 | 700 |
| 2 | 2015-01-14 | 300 |
| 2 | 2015-01-15 | 150 |
| 2 | 2015-02-05 | 90 |
| 2 | 2015-02-11 | 100 |
| 3 | 2015-01-01 | 900 |
| 3 | 2015-01-15 | 150 |
+----+------------+------+
Generate an SQL query to produce the following output.
+------------+----+------------+------+---------------+--------------------+
| Row_number | ID | Date | Used | Running Total | RemainingAllotment |
+------------+----+------------+------+---------------+--------------------+
| 1 | 1 | 2015-01-01 | 800 | 800 | 200 |
| 2 | 1 | 2015-01-14 | 300 | 1100 | -100 |
| 3 | 1 | 2015-01-15 | 100 | 100 | 1400 |
| 4 | 1 | 2015-01-18 | 200 | 300 | 1200 |
| 5 | 2 | 2015-01-01 | 700 | 700 | 500 |
| 6 | 2 | 2015-01-14 | 300 | 1000 | 200 |
| 7 | 2 | 2015-01-15 | 150 | 1150 | 50 |
| 8 | 2 | 2015-02-05 | 90 | 90 | -90 |
| 9 | 2 | 2015-02-11 | 100 | 100 | 900 |
| 10 | 3 | 2015-01-01 | 900 | 900 | 100 |
| 11 | 3 | 2015-01-15 | 100 | 1000 | 0 |
| 12 | 3 | 2015-01-15 | 50 | 50 | 1450 |
+------------+----+------------+------+---------------+--------------------+
Some details for the desired output:
- On Row_number 2, it is negative 100, since he used up all hist allotment
- On Row_number 3, he has new allotment from the start of this date, running total should be reset on this ID
- On Row_number 8, its negative 90, reset running total for this ID, since Surrkey 3 was expired, and startdate will only be in 2015-02-10
- On Row_number 9, new usage for Surrkey 4 on table A
Additional requirements. I edited the sample table for this
- On Row_Number 11 and 12, There are same date and same ID, since you have to use all remaining allotment before using the next one, in this case, the Surrkey 6.