By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table mytable(id int, received_by int, sent_by int, amount int, product_id int);
insert into mytable values(1, 1, 2, 10, 1);
insert into mytable values(2, 1, 3, 12, 1);
insert into mytable values(3, 2, 1, 5, 1);
insert into mytable values(4, 3, 1, 8, 2);
select product_id, (coalesce(received,0)-coalesce(sent,0)) as Quantity, coalesce(received,0) received,coalesce(sent)sent
from
( select
product_id,
sum(case when received_by = 1 then amount end) as received,
sum(case when sent_by = 1 then amount end) as sent
from mytable
group by
product_id
)t;
product_id | Quantity | received | sent |
---|---|---|---|
1 | 17 | 22 | 5 |
2 | -8 | 0 | 8 |