简体   繁体   中英

2 Mysql table sum column Group and subruction pls

have

1.Table is.

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.

McName    McModel   McOut
============================
 CPU   |   i5     |   1
 RAM   |   8GB    |   3
  1. I want to Same Group Name and same Model SUM then 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 :

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. Then a LEFT JOIN between this result and Table2 would get the corresponding McOut value for each <MgName,MgModel> pair (if exists in Table2 ).

Finally the difference of the summed value and McOut would make final result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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