简体   繁体   English

2 Mysql表的总和列Group和subrution pls

[英]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
  1. I want to Same Group Name and same Model SUM then MgIn - MgOut 我想要相同的组名和相同的模型SUM,然后输入MgIn-MgOut

= =

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 : 您可以简单地使用UNIONGROUP 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 valueMcOutMcOut最终结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM