'How to subtract a data from multiple columns by considering previous remainder and display the subtracted value in PLSQL

enter image description here

I have this set of data where I want to sum BT(which is 0.8) data on Year,Month,EID basis and then subtract it in IN & display how much IN is subtracted as -ve value, then remaining(0.5) subtract from MT & display how much MT is subtracted as -ve value, then remaining(0.4) subtract from NLT & display how much NLT is subtracted as -ve value, then remaining if left (0.2) from VT & display how much VT is subtracted as -ve value,

Please note, the subtraction happens in sequence IN>MT>NLT>VT

Sample query for you to create dataset

CREATE TABLE table_name (year, month, eid, bt, "IN", mt, nlt, vt) AS
SELECT 2022, 1, 123456, 0.8, 0.3, 0.1, 0.2, 0.2 FROM DUAL UNION ALL
SELECT 2022, 2, 123456, 0.8, 0.3, 0.1, 0.2, 0.1 FROM DUAL UNION ALL
SELECT 2022, 3, 123456, 0.8, 0.3, 0.1, 0.2, 0.3 FROM DUAL UNION ALL
SELECT 2022, 4, 123456, 0.8, 0.3, 0.1, 0.5, 0.3 FROM DUAL;


Solution 1:[1]

You don t need plsql u need simple (sum, group by) sql query on that table

select (sum(bt)-sum("IN")) as in_ve, 
       (sum(bt)-sum("IN")-sum(mt)) as mt_ve,
       (sum(bt)-sum("IN")-sum(mt)-sum(nlt)) as nlt_ve,
       (sum(bt)-sum("IN")-sum(mt)-sum(nlt)-sum(vt)) as vt_ve 
from table_name group by year, month, eid;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1