I’m using MS SQL Server and I have 2 tables.
Supply_list
sl_id(pk) supply_id(fk)* transaction_id Qty
1 14 872670099 3
2 15 872670100 5
3 16 872670101 1
4 16 872670105 4 <
- supply_id is a foreign key to the supply_id in amenity table
Supply
supply_id(pk) no_of_units
----------------------------
13 2
14 3
15 6
16 10
The output should be supply_id then the no. of units available which is equal to No_of_units subtracted by the Qty.
output
id units available
-------------------------
13 2
14 0 --> [1]
15 1
16 5 --> [2]
[1] Since based on the supply_list table supply_id 14 has 3 for its Qty
[2] There are two records that contains supply_id 16 so we have to add their qty which are 4 and 1 so we have 5. And that 5 would be subtracted from the no_of_units of supply_id 16 and we will get 5 for units available.
Something like
This makes the aggregate more obvious but is the same query