Question

Est-il possible de créer une requête qui ajoute des valeurs dans deux tableaux:

Par exemple, supposons que vous ayez deux tables

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

et

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

Ensuite, lorsque vous ajoutez les deux tables, vous obtenez le résultat correspondant à l'identifiant. Donc, a = 1 + 1 = 2, et simplement le même résultat où ils ne le font pas. La requête renverrait donc:

id     value
--     -----
a       2
b       2
c       5
d       7
e       5
f       4
g       5
Était-ce utile?

La solution

peut-être quelque chose comme

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

Autres conseils

Utiliser:

  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

Vous pouvez le faire comme ceci - mais les autres réponses sont probablement plus rapides:

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

OU

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

Pas de regroupement ou quoi que ce soit. Il gère les cas suivants

si un identifiant est dans T1 mais pas dans T2, vous obtiendrez la valeur dans T1 et vice versa. Ceci gère l'inclusion bidirectionnelle.

Si un identifiant figure dans les deux, vous obtiendrez la somme

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top