[英]2 Mysql table sum column Group and subruction pls
have 有
1.Table is. 1.表是。
MgName MgModel MgIn
============================
CPU | i5 | 1
RAM | 8GB | 1
BOARD | ASUS | 1
CPU | i5 | 2
RAM | 4GB | 1
RAM | 8GB | 1
CPU | i7 | 1
2.Table is. 2.表是。
McName McModel McOut
============================
CPU | i5 | 1
RAM | 8GB | 3
= =
StckName StckModel StckPce
============================
CPU | i5 | 2
RAM | 8GB | -1
BOARD | ASUS | 1
CPU | i7 | 1
RAM | 4GB | 1
You can simple use UNION
and a GROUP BY
clause instead of joining : 您可以简单地使用
UNION
和GROUP BY
子句来代替加入:
SELECT t.StckName ,t.StckModel,SUM(t.Mg) as StckPce
FROM(SELECT MgName as StckName ,MgModel,MgIn as mg as StckModel
FROM Table1
UNION ALL
SELECT McName ,McModel,mcOut*-1
FROM Table2) t
GROUP BY t.StckName ,t.StckModel
Here's the query: 这是查询:
SELECT
t.MgName AS StckName,
t.MgModel AS StckModel,
t.summedValue - IFNULL(Table2.McOut,0) AS StckPce
FROM
(
SELECT
MgName,
MgModel,
SUM(MgIn) summedValue
FROM Table1
GROUP BY MgName,MgModel
) t
LEFT JOIN Table2 ON t.MgName = Table2.McName AND t.MgModel = Table2.McModel;
The inner query gets the summed value for each <MgName,MgModel>
pair. 内部查询获取每个
<MgName,MgModel>
对的<MgName,MgModel>
。 Then a LEFT JOIN
between this result and Table2
would get the corresponding McOut
value for each <MgName,MgModel>
pair (if exists in Table2
). 然后,此结果与
Table2
之间的LEFT JOIN
将为每个<MgName,MgModel>
对获取相应的McOut
值(如果Table2
存在)。
Finally the difference of the summed value
and McOut
would make final result. 最终,
summed value
与McOut
将McOut
最终结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.