将两个表之和的结果相加

时间:2014-02-25 10:52:57

标签: mysql sql sql-server

我不知道如果标题是好的,但无论如何,我想知道我们是否可以在将重复项与另一个表相加之后添加表的总和,如下例所示:

表A:

  Date          BL          Client  Design      Ref1    Ref2    Ref3    Qte
  14/01/2013    13011401    A       VT          VT1     JAUNE   XL      3
  14/01/2013    13011402    B       VT          VT2     GRIS    L       62
  16/01/2013    13011601    D       VT          VT1     GRIS    L       10
  19/01/2013    13011903    F       VT          VT2     JAUNE   L       15

表B:

  Date          BL          Client  Design      Ref1    Ref2    Ref3    Qte
  14/01/2013    13011401    A       VT          VT1     JAUNE   XL      3
  14/01/2013    13011402    B       VT          VT2     GRIS    L       100
  16/01/2013    13011601    D       VT          VT1     GRIS    L       10
  19/01/2013    13011903    F       VT          VT2     JAUNE   L       15

结果:

  Date          BL          Client  Design      Ref1    Ref2    Ref3    Qte
  14/01/2013    13011401    A       VT          VT1     JAUNE   XL      6
  14/01/2013    13011402    B       VT          VT2     GRIS    L       162
  16/01/2013    13011601    D       VT          VT1     GRIS    L       20
  19/01/2013    13011903    F       VT          VT2     JAUNE   L       30

条件是( Client,Design,Ref1,Ref2,Ref3 )在两个表中应该相同!

3 个答案:

答案 0 :(得分:0)

您可以尝试使用JOINS

SELECT 
    TableA.Date,
    TableA.BL,
    TableA.Client,
    TableA.Design,
    TableA.Ref1,
    TableA.Ref2,
    TableA.Ref3,
    TableA.Qte + TableB.Qte As Qte
FROM
    TableA
        JOIN
    TableB ON TableA.Client = TableB.Client
        AND TableA.Design = TableB.Design
        AND TableA.Ref1 = TableB.Ref1
        AND TableA.Ref2 = TableB.Ref2
        AND TableA.Ref3 = TableB.Ref3;

答案 1 :(得分:0)

我想这就是你想要的

select t.Date,t.BL,t.Client,t.Design,t.Ref1,t.Ref2,t.Ref3, t.Qte+t1.Qte as qte
from table1 t inner join table2 t1
on t.client=t1.client and
   t.design=t1.design and
   t.ref1=t1.ref1 and
   t.ref2=t1.ref2 and
   t.ref3=t1.ref3;

答案 2 :(得分:0)

这是另一种方法。它可以扩展为处理两个以上的表。

SELECT   Date, BL, Client, Design, Ref1, Ref2, Ref3, SUM(Qte) Qte
FROM (
  SELECT Date, BL, Client, Design, Ref1, Ref2, Ref3, Qte FROM TableA
  UNION ALL
  SELECT Date, BL, Client, Design, Ref1, Ref2, Ref3, Qte FROM TableB
) t
GROUP BY Date, BL, Client, Design, Ref1, Ref2, Ref3, Qte