从两个不同的表sql获得总和

时间:2011-02-03 08:00:21

标签: sql

我有两个名为stock_in和stock_out的表,其中包含以下列:

stock_in (recid,itemid,units)

stock_out (recid,itemid,units)

我想要的是从两个表中获得单位总和,然后计算从stock_in到stock_out的剩余单位,我可以为任何项目指定itemid

由于

4 个答案:

答案 0 :(得分:4)

SELECT
  (SELECT SUM(units) FROM stock_in WHERE itemid = 7) -
  (SELECT SUM(units) FROM stock_out WHERE itemid = 7)
  AS difference;

答案 1 :(得分:2)

select
    stock_in.itemid,
    sum_stock_in.sum as sum_in,
    sum_stock_in.sum as sum_out
from
    stock_in
    left join (
        select itemid, sum(units) as sum from stock_in group by itemid
    ) as sum_stock_in on sum_stock_in.itemid = stock_in.itemid
    left join (
        select itemid, sum(units) as sum from stock_out group by itemid
    ) as sum_stock_out on sum_stock_out.itemid = stock_in.itemid
where
    stock_in.itemid in (1, 2, 3)

-- edit:
group by
    stock_in.itemid

在此查询中,假设stock_out是stock_in的子集,即stock_in包含每个可能的itemid。

答案 2 :(得分:1)

从中制作存储过程

SELECT @SUM1=SUM(*)
FROM STOCK_IN
SELECT @SUM2=SUM(*)
FROM STOCK_OUT

SELECT @SUM1-@SUM2

这是我能想到的最佳解决方案,Dan提到的那个解决方案因为使用了两个而没有工作,实际完成的工作是内部连接

答案 3 :(得分:1)

因为这是在PHP下:

$queryString = "SELECT
  SUM(stock_in.units) - SUM(stock_out.units) as difference
FROM
  stock_in
INNER JOIN stock_out
ON stock_in.itemid=stock_out.itemid
WHERE stock_in.itemid = ".$value_to_query;
$result = mysql_query($queryString);

试验:

create database sumgetter;
use sumgetter;
CREATE TABLE stock_in (
         recid INT,
         itemid INT,
         units INT
);
CREATE TABLE stock_out (
         recid INT,
         itemid INT,
         units INT
);
INSERT INTO stock_in VALUES (1, 1, 2);
INSERT INTO stock_out VALUES (1, 1, 3);
INSERT INTO stock_in VALUES (2, 2, 2);
INSERT INTO stock_out VALUES (2, 2, 2);

SELECT
  SUM(stock_in.units) - SUM(stock_out.units) as difference
FROM
  stock_in
INNER JOIN stock_out
ON stock_in.itemid=stock_out.itemid
WHERE stock_in.itemid = 1;

//结果

+------------+
| difference |
+------------+
|         -1 |
+------------+
1 row in set (0.00 sec)