如何在主键上添加/合并两个表?

时间:2016-05-24 21:00:52

标签: sql-server tsql

我是一个全新的SQL新手。我有两张桌子。每个表都有一个主键列(ID)和其他几个带整数值的列。

例如:

enter image description here

enter image description here

现在我想将两个表合并到一个表中 - 以每个ID添加所有苹果,香蕉和西红柿的方式。

例如:

enter image description here

此任务的SQL语句如何?

4 个答案:

答案 0 :(得分:5)

    INSERT INTO NEWTABLE (ID, Apples, Bananas, Tomatoes)
     SELECT ISNULL(a.Id, b.Id) as [Id], 
             ISNULL(a.Apples,0) + ISNULL(b.Apples,0) AS [Apples], 
             ISNULL(a.Bananas,0) + ISNULL(b.Bananas,0) AS [Bananas], 
             ISNULL(a.Tomatoes,0) + ISNULL(b.Tomatoes,0) AS [Tomatoes]
    FROM Table1 AS a
    FULL OUTER JOIN Table2 AS b on b.Id = a.Id

我认为这将解决您的问题。只需INSERTSELECT合并。

答案 1 :(得分:3)

没时间测试它,但我会使用UNION和GROUP BY:

SELECT ID,
    SUM(APPLES) AS APPLES,
    SUM(BANANAS) AS BANANAS,
    SUM(TOMATOES) AS TOMATOES
FROM
    (SELECT * FROM TABLEA 
              UNION ALL
     SELECT * FROM TABLEB ) AS ALL
GROUP BY ID

如果有效,首先会创建一个包含所有条目的表,然后将具有相同ID的表组合在一起。如果有问题,任何人都可以自由编辑。

没看到你想要第三张表,那么你不需要列别名:

INSERT INTO
    TABLEC
VALUES
    (ID, APPLES, BANANAS, TOMATOES)
SELECT ID,
    SUM(APPLES),
    SUM(BANANAS),
    SUM(TOMATOES)
FROM
    (SELECT * FROM TABLEA 
              UNION ALL
     SELECT * FROM TABLEB) AS ALL
GROUP BY ID

如果这不起作用,您可以执行其中一个JOIN答案,但会将其更改为TABLEA JOIN TABLEB USING(ID)。

答案 2 :(得分:1)

最好的方法是使用完全外连接,否则你可能会错过一些id。在您的示例中,使用左连接时您将错过id = 4,而使用右连接时您将错过id = 2。

另外要小心ID,如果存在则要从Table1获取,否则从Table2获取

所以我认为最好的解决方案是这样的:

INSERT INTO Table3 (ID, Apples, Bananas, Tomatoes)
SELECT  coalesce (a.Id, b.Id) 
coalesce(a.Apples, 0) + coalesce(b.Apples, 0)  AS Apples, 
coalesce(a.Bananas, 0) + coalesce(b.Bananas, 0) AS Bananas, 
coalesce(a.Tomatoes, 0) + coalesce(b.Tomatoes, 0) AS Tomatoes, 
FROM Table1 a
FULL OUTER JOIN Table2 b on b.Id = a.Id

答案 3 :(得分:0)

试试这个

insert into tableC (ID, Apples, Bananas, Tomatoes)
select tableA.ID,
       ISNULL(tableA.Apples,0) + ISNULL(tableB.Apples,0) as Apples,
       ISNULL(tableA.Bananas,0) + ISNULL(tableB.Bananas,0) as Bananas,
       ISNULL(tableA.Tomatoes,0) + ISNULL(tableB.Tomatoes,0) as Tomatoes
from tableA left join tableB
on tableA.ID = tableB.ID;