在mySQL中使用SUM()和UNION ALL来获取多个sum列

时间:2016-01-21 14:42:57

标签: php mysql sum union-all

我有四个表,所有表都包含以下列:
'地点'
'sortiment'
'amount_in'(数字)
'amount_out'(数字)

所有这些都代表了木材加工的不同情况,例如生产,储存,铁路车辆装载等,仅供参考。使用不同的SUM(in-out)查询,我可以看到每个位置中不同木材分拣的数量。但是,每次添加新位置时,我都必须手动添加新查询,例如新的日志记录区域。基本上这些表都是相似的,所以我可以使用UNION ALL来总结所有地方!

现在我想做的是创建一个包含单个查询的表,基本上看起来像这样:

|             | location A | location B | location C |
|-------------|------------|------------|------------|
| sortiment A |  sum(AA)   |  sum(AB)   |  sum(AC)   |
| sortiment B |  sum(BA)   |  sum(BB)   |  sum(BC)   |
| sortiment C |  sum(CA)   |  sum(CB)   |  sum(CC)   |

所有表都包含所有排序,但每个表都有不同的位置。

这是我先试过的:

SELECT location, sortiment, SUM(amount_in-amount_out)
FROM (
SELECT location, sortiment, amount_in, amount_out FROM Eproduction 
UNION ALL
SELECT location, sortiment, amount_in, amount_out FROM Estorage 
UNION ALL
SELECT location, sortiment, amount_in, amount_out FROM Elogdepot
UNION ALL
SELECT location, sortiment, amount_in, amount_out FROM Erailway
) x
GROUP by location";

然后循环

echo "<tr><td>".$row['sortiment']. "</td><td>" .(float)$row['SUM(amount_in-amount_out)']."</td></tr>";

显然导致了这个

| sortiment A | sum(AA) |
| sortiment B | sum(BA) |
| sortiment C | sum(CA) |
| sortiment A | sum(AB) |
| sortiment B | sum(BB) |
| sortiment C | sum(CB) |etc

这不是我想要达到的目标。

然后我尝试了别名:

SELECT location, sortiment, 
SUM(in_pr-out_pr), 
SUM(in_sto-out_sto), 
SUM(in_log-out_log), 
SUM(in_rail-out_rail)
FROM (
SELECT location, sortiment, amount_in AS in_pr, amount_aout AS out_pr FROM Eproduction 
UNION ALL
SELECT location, sortiment, amount_in AS in_sto, amount_out AS out_sto FROM Estorage 
UNION ALL
SELECT location, sortiment, amount_in AS in_log, amount_out AS out_log FROM Elogdepot
UNION ALL
SELECT location, sortiment, amount_in AS in_rail, amount_out AS out_rail FROM Erailway
) x
GROUP by location, sortiment";

然后循环

echo "<tr><td>".$row['location']. "</td><td>".$row['sortiment']. "</td><td>" .(float)$row['SUM(in_pr-out_pr)']."</td><td>" .(float)$row['SUM(in_sto-out_sto)']."</td><td>" .(float)$row['SUM(in_log-out_log)']."</td><td>" .(float)$row['SUM(in_rail-out_rail)']."</td></tr>";

在我的理解中应该创建我想要的表,但是它会返回'unknown field'in_sto''错误。

任何帮助表示感谢,提前谢谢!

0 个答案:

没有答案