2 Mysql表总和列组和子程序

时间:2016-06-09 08:16:44

标签: php mysql sql

1.Table is。

db.User_CV.Add(new User_CV
{
   Cv_Path = Request.Files[0].FileName
});
db.SaveChanges();

db.User_Account.Add(new User_Account {
     //Cv_ID = model.Cv_ID,
     Full_Name = model.Full_Name,
     Email = model.Email,
     Contact_No = model.Contact_No,
     Password = model.Password,
     Fuctional_Area = model.Fuctional_Area
});
 db.SaveChanges();

2.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
  1. 我想要相同的组名称和相同的模型SUM然后MgIn - MgOut
  2. =

    McName    McModel   McOut
    ============================
     CPU   |   i5     |   1
     RAM   |   8GB    |   3
    

2 个答案:

答案 0 :(得分:1)

您可以简单地使用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

答案 1 :(得分:1)

以下是查询:

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;

内部查询获取每个<MgName,MgModel>对的求和值。然后,此结果与LEFT JOIN之间的Table2将获得每个McOut对的相应<MgName,MgModel>值(如果存在于Table2中)。

最后,summed valueMcOut的差异将产生最终结果。