0

我有两个 sql 表,purchase并且sent,我想知道任何日期的项目的未结余额。为此,我试图采取sum(puchase.quantity) - sum(sent.quantity) where date<some date. 我可以有单独的查询,但我不知道如何组合它们。

以下是个别查询:

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

请告诉我是否有更好的方法来获得未结余额。

提前致谢。

4

2 回答 2

1

也许有一种更简洁的方法可以得到你想要的东西,但是下面应该会给你正确的结果:

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
于 2013-09-14T22:28:23.217 回答
1

我想你想要这个

这是工作演示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
于 2013-09-14T19:04:02.467 回答