统计来自不同表的值

时间:2015-02-17 14:58:39

标签: sql

我想计算表中的值减去另一个表中的计数值。每件/部分

我试过这个:

SELECT SUM(receipt) AS "receipt"
FROM receipt WHERE item = '".$partnumber."'
group by item

这适用于一个表,但我如何使用2个表?

表收据:

item | receipt
100    5
100    2
200    10

表销售

part | sold
100    2

输出:

partnumber | stock
100          5

所以我想计算每件物品/零件的总和,并且我想要为库存做收据卖出。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

收取收据的总和:

SELECT item, SUM(receipt) receipt
FROM Table1 t1
GROUP BY item

然后是销售总额:

SELECT part, SUM(sold) sold
FROM Table2 t2
GROUP BY part

然后将他们加在一起,带来差异:

SELECT t1.item, (t1.receipt - COALESCE(t2.sold,0)) AS stock
FROM
(
    SELECT item, SUM(receipt) AS receipt
    FROM Table1 t1
    GROUP BY item
) t1
LEFT JOIN
(
    SELECT part, SUM(sold) AS sold
    FROM Table2 t2
    GROUP BY part
) t2
ON t1.item = t2.part

请注意,如果给定零件没有销售,COALESCE将使销售额为0。