2

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

例如,假设您有两个表

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
4

5 回答 5

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
于 2009-10-30T04:02:13.400 回答
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
于 2009-10-30T04:14:42.673 回答
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)
于 2009-10-30T04:36:53.690 回答
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

或者

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
于 2009-10-30T05:25:28.537 回答
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 中获得值,反之亦然。这处理双向包含。

如果两者都有一个ID,您将得到总和

于 2009-10-30T13:24:15.307 回答