开发者

Merge and add values from two tables

开发者 https://www.devze.com 2022-12-10 00:19 出处:网络
Is it possible to craft a query that adds values within two tables: For example, say you have two tables

Is it possible to craft a query that adds values within two tables:

For example, say you have two tables

id    value
--    -----
a开发者_如何学Go       1
c       2
d       3
f       4
g       5

and

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

Then when you 'add' the two tables you would get the result where the id's match. So, a=1+1=2, and simply the same result where they don't. So the query would return:

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


maybe something like

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


Use:

  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


You could do it like this - but the other answers are probably swifter:

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)


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


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

No grouping or anything. It handles the following cases

if an id is in T1 but not in T2 you will get the value in T1 and vice versa. This handles bi-directional inclusion.

If an ID is in both you will get the sum

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号