You can use the SUM
analytic function to generate a cumulative total and subtract that from the maximum to see how much capacity you have remaining and then use GREATEST
and LEAST
to restrict the value to be between 0
and the c
column value:
SELECT a, b, c,
LEAST(
c,
GREATEST(
a + c - SUM(c) OVER (PARTITION BY a ORDER BY b),
0
)
) AS d
FROM table_name
Which, for the sample data:
CREATE TABLE table_name (a, b, c) AS
SELECT 6000, 1, 3000 FROM DUAL UNION ALL
SELECT 6000, 2, 2000 FROM DUAL UNION ALL
SELECT 6000, 3, 4000 FROM DUAL UNION ALL
SELECT 6000, 4, 2500 FROM DUAL UNION ALL
SELECT 9000, 5, 3000 FROM DUAL UNION ALL
SELECT 9000, 9, 2000 FROM DUAL UNION ALL
SELECT 9000, 15, 3000 FROM DUAL UNION ALL
SELECT 9000, 17, 2500 FROM DUAL;
Outputs:
A |
B |
C |
D |
6000 |
1 |
3000 |
3000 |
6000 |
2 |
2000 |
2000 |
6000 |
3 |
4000 |
1000 |
6000 |
4 |
2500 |
0 |
9000 |
5 |
3000 |
3000 |
9000 |
9 |
2000 |
2000 |
9000 |
15 |
3000 |
3000 |
9000 |
17 |
2500 |
1000 |
fiddle