I have two sql tables, purchase
and sent
, I want to know the outstanding balance of items at any date. For this I am trying to take sum(puchase.quantity) - sum(sent.quantity) where date<some date
. I can have individual queries but I dont know how to combine them.
Here are individual queries:
select item,sum(quantity) from sent where datee <'some date' group by item
select item,sum(quantity) from purchase where datee<'some date' group by item
Please tell me if there is aa better way to get the outstanding balance.
Thanks in advance.
I think you want this
Here is working demo SQLFiddle
CREATE TABLE sent
(
item int,
quantity int
);
CREATE TABLE purchase
(
item int,
quantity int
);
insert into sent values(1,4);
insert into sent values(2,7);
insert into sent values(3,9);
insert into sent values(4,5);
insert into sent values(5,9);
insert into purchase values(1,2);
insert into purchase values(2,5);
insert into purchase values(3,3);
insert into purchase values(4,2);
insert into purchase values(5,7);
select sent.item , (sum(IFNULL(sent.quantity,0)) - sum(IFNULL(purchase.quantity,0))) as diff
FROM sent , purchase Where sent.item = purchase.item group by sent.item
Maybe there's a more succint way to get what you want, but the folliwing should give you correct results:
SELECT s.item,
s.qty as total_sent,
COALESCE(p.qty,0) as total_purchase,
s.qty - COALESCE(p.qty,0) as stock
FROM
(
SELECT item, sum(quantity) as qty
FROM sent
GROUP BY item
) s
LEFT JOIN
(
SELECT item, sum(quantity) as qty
FROM purchase
GROUP BY item
) p
ON p.item = s.item
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.