sql server - SUM aggregate function and Subquery -SQL -
i'm using ms sql server , 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 foreign key supply_id in amenity table
supply
supply_id(pk) no_of_units ---------------------------- 13 2 14 3 15 6 16 10 the output should supply_id no. of units available equal no_of_units subtracted qty.
output
id units available ------------------------- 13 2 14 0 --> [1] 15 1 16 5 --> [2] [1] since based on supply_list table supply_id 14 has 3 qty
[2] there 2 records contains supply_id 16 have add qty 4 , 1 have 5. , 5 subtracted no_of_units of supply_id 16 , 5 units available.
- you left outer join list table parent table
- subtract sum of list qty values parent no_of_units value
- use isnull in case there no list rows
something like
select s.supply_id, s.no_of_units - isnull(sum(sl.qty), 0) [units available] supply s left join supply_list sl on s.supply_id = sl.supply_id group s.supply_id, s.no_of_units this makes aggregate more obvious same query
select s.supply_id, s.no_of_units - isnull(sl.sumlistqty, 0) [units available] supply s left join ( select supply_id, sum(qty) sumlistqty supply_list group supply_id ) sl on s.supply_id = sl.supply_id
Comments
Post a Comment