合并并添加两个表中的值

时间:2009-10-30 03:59:05

标签: sql addition

是否可以制作一个在两个表中添加值的查询:

例如,假设你有两张桌子

id    value
--    -----
a       1
c       2
d       3
f       4
g       5

id     value
--     -----
a        1
b        2
c        3
d        4
e        5

然后当你'添加'这两个表时,你会得到id匹配的结果。因此,a = 1 + 1 = 2,并且只是相同的结果,而不是。所以查询将返回:

id     value
--     -----
a       2
b       2
c       5
d       7
e       5
f       4
g       5

5 个答案:

答案 0 :(得分:5)

可能像

select coalesce(t1.id, t2.id) as id, (coalesce(t1.value, 0) + coalesce(t2.value, 0)) as value 
from table1 t1 full outer join table2 t2 on t1.id = t2.id

答案 1 :(得分:2)

使用:

  SELECT x.id,
         SUM(x.value)
    FROM (SELECT t.id,
                 t.value
            FROM TABLE_1 t
          UNION ALL
          SELECT t2.id,
                 t2.value
            FROM TABLE_2 t2) x
GROUP BY x.id

答案 2 :(得分:1)

你可以这样做 - 但其他答案可能更快:

SELECT t1.id, t1.value + t2.value AS value
  FROM t1 INNER JOIN t2 ON t1.id = t2.id
UNION
SELECT t1.id, t1.value
  FROM t1
 WHERE t1.id NOT IN (SELECT t2.id FROM t2)
UNION
SELECT t2.id, t2.value
  FROM t2
 WHERE t2.id NOT IN (SELECT t1.id FROM t1)

答案 3 :(得分:0)

SELECT
    COALESCE(t1.id, t2.id) AS id,
    COALESCE(t1.value, 0) + COALESCE(t2.value, 0) AS value
FROM
    t1
    FULL OUTER JOIN
    t2 ON t1.id = t2.id

OR

SELECT
    foo.id,
    COALESCE(t1.value, 0) + COALESCE(t2.value, 0) AS value
FROM
    (
    SELECT t1.id FROM t1
    UNION
    SELECT t2.id FROM t2
    ) foo
    LEFT JOIN
    t1 ON foo.id = t1.id
    LEFT JOIN
    t2 ON foo.id = t2.id

答案 4 :(得分:0)

SELECT ISNULL(T1.Col1.T2.Col1) as ID, (ISNULL(T1.Col2,0) + ISNULL(T2.Col2,0)) as SumCols
FROM T1 OUTER JOIN T2 ON T1.Col1 = T2.Col2

没有分组或任何东西。它处理以下情况

如果id在T1中而不在T2中,您将获得T1中的值,反之亦然。这可以处理双向包含。

如果同时存在身份证,您将获得总和