计算不同表格的总和

时间:2015-01-21 11:50:24

标签: mysql

我有两张桌子:

我的收据

Partnumber | Receipt | Location

销售表:

Partnumber | Sales | Location

我想要做的是计算每个地点和每个零件号的库存数量。我有一个表的查询:

在这里,我按照部件编号计算该位置的收据部件

SELECT Location, sum(Receipt) FROM receipt WHERE Partnumber = 100 GROUP BY Location

您需要对sales表执行相同的操作。最后,我想根据每个地点的收据表计算总和 - 每个地点的销售表总和。

数据:

Partnumber | Receipt | Location

100          2         500
100          5         500
100          2         300
200          4         600
300          8         500


Partnumber | Sales | Location

100          1         500
300          4         500
100          1         300

这是输出:

Partnumber | stock |  location
100          6        500
100          1        300
200          4        600
300          4        500

因此,请根据每个地点的部件号减去每个地点的部件号计数销售数来计算收据物品。这可以用一个查询吗?

2 个答案:

答案 0 :(得分:3)

您已经知道如何计算收到的零件总数:

SELECT Location, SUM(Receipt)
FROM receipt WHERE Partnumber = 100 GROUP BY Location ;

计算销售的零件总数类似:

SELECT Location, SUM(Sales)
FROM sales WHERE Partnumber = 100 GROUP BY Location ;

现在您只需要计算差异,所需要的就是组合上述两个查询:

SELECT Location, (receipt_count - COALESCE(sales_count, 0)) AS current_stock
FROM (
    SELECT Location, SUM(Receipt) AS receipt_count
    FROM receipt WHERE Partnumber = 100 GROUP BY Location
) AS Receipt
LEFT JOIN
 (
    SELECT Location, SUM(Sales) AS sales_count
    FROM sales WHERE Partnumber = 100 GROUP BY Location
) AS Sales USING (Location)

答案 1 :(得分:0)

Union可以解决这个问题:

(SELECT Partnumber, Receipt as quantity, Location FROM receipt)
UNION
(SELECT Partnumber, (-Sales) as quantity, Location FROM sales)

这将返回

PARTNUMBER | QUANTITY | LOCATION
    100    |       2  | 500
    100    |       5  | 500
    200    |       4  | 600
    300    |       8  | 500
    100    |      -1  | 500
    300    |      -4  | 500

注意,我如何从销售表中为数量设置负值。

现在有了这个,你可以做你需要的:

SELECT DISTINCT Partnumber, sum(quantity) as Stock, Location FROM
(
    (SELECT Partnumber, Receipt as quantity, Location FROM receipt)
    UNION
    (SELECT Partnumber, (-Sales) as quantity, Location FROM sales)
) as UnitedTable
GROUP BY Partnumber, Location;

别忘了按位置和部分号码分组。 结果:

PARTNUMBER | STOCK | LOCATION
      100  |    6  | 500
      200  |    4  | 600
      300  |    4  | 500

http://sqlfiddle.com/#!2/76193d/19