7

我有两个表 A 和 B。A 有两列:id、amount。B也有两列:id,amount。我希望将 A 和 B 结合起来创建一个新表 C,具有相同的两列:id、amount。我怎样才能使用 SQL 来做到这一点?例如:

A
    ('A1',1)
    ('A2',5)
    ('A3',2)
    ('A4',5)
    ('A5',2)
    ('A6',7)
B
    ('A1',3)
    ('A3',2)
    ('A4',7)
    ('A5',4)
    ('A8',2)
    ('A9',10)

所以 C 应该是:

C
    ('A1',4)
    ('A2',5)
    ('A3',4)
    ('A4',12)
    ('A5',6)
    ('A6',7)
    ('A8',2)
    ('A9',10)

谢谢!

4

2 回答 2

10
SELECT  ID, SUM(Amount) total
FROM
        (
            SELECT ID, Amount FROM A
            UNION ALL
            SELECT ID, AMount FROM B
        ) s
GROUP   BY ID

您可以根据查询结果创建表。

CREATE TABLE C
AS
SELECT  ID, SUM(Amount) total
FROM
        (
            SELECT ID, Amount FROM A
            UNION ALL
            SELECT ID, AMount FROM B
        ) s
GROUP   BY ID;
于 2013-02-23T09:14:30.200 回答
-1

上面的答案绝对没问题。只需向其中添加一个按 ID 排序的 order by 子句。

SELECT  ID, SUM(Amount) as total
FROM
        (
            SELECT ID, Amount FROM A
            UNION ALL
            SELECT ID, AMount FROM B
        ) s
GROUP by ID
order by ID 
于 2013-07-31T15:42:55.503 回答