2009-10-30 184 views
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 

回答

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 
+0

我想你可能需要一個完全外部連接,而不是左連接 – 2009-10-30 04:07:48

+0

我想你是對 – 2009-10-30 04:08:05

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 
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) 
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 
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在這兩個你會得到的總和

+0

我想你會發現ISNULL更快的索引數據比COALESCE。應該把這作爲這個職位的理由 – TerrorAustralis 2009-10-30 13:27:26