SQL: sum(unit) table a minus sum(unit) table b
-
28-10-2019 - |
Question
I have 2 tables;
- item_in(item_id,unit)
- item_out(item_id,unit)
Now let say I want to know how many unit is being insert for every item, I just query
select sum(unit) from item_in order by item_id
Likewise, if I want to know how many unit is being taken out, I just query
select sum(unit) from item_out order by item_id
I don't know how to query the balance (item_in - item_out) for each item.
It is great if I can make all the query in one stored procedure, because I want to call the procedure using DataWindow.
Please help, thank you.
Solution
SELECT
item_id,
SUM(unit) AS unit_balance
FROM (
SELECT item_id, unit FROM item_in
UNION ALL
SELECT item_id, -unit FROM item_out
) AS s (item_id, unit)
GROUP BY item_id
OTHER TIPS
I know nothing about sybase, but this, or a subtle variation of this, should work.
select t1.item_id, sum(t1.unit - coalesce(t2.unit, 0)) as Balance
from item_in t1
left join item_out t2
on t1.item_id = t2.item_id
group by t1.item_id
Coalesce will put a 0 whenever a unit from t2 is NULL, so that you can properly substract the item_in unit amount from it.
Note: This works in SQL Server. I don't know if you might find any syntactic difference when running it in sybase :(
i hope the following query works:
select
sum(inn.unit) - sum(outt.unit)
from item_in inn
inner join item_out outt on inn.item_id = outt.item_id