how to add different record values?

Asked

Viewed 1,902 times

1

I’m trying to add the value of id 1 and the value2 of id 2 which in this case would be equal to 220, as I do this consultation?

       ID      VALOR     VALOR2
---------- ---------- ----------
         1        110        100
         2        100        110

this was the select I was trying to, but not the right one

select valor+valor2 from teste3 where valor = (select valor from teste3 where id = 1 and valor2 = (select valor2 from teste3 where id = 2))
  • is the value of ID 1 + VALOR2 of ID 2, in case 110+110

  • https://docs.microsoft.com/pt-br/sql/t-sql/queries/select-over-clause-transact-sql use the OVER()

  • I don’t understand what you need, a cumulative total ? a general total ?

1 answer

2


SELECT SUM(x.valor) AS total
  FROM (
    SELECT valor FROM teste3 WHERE id = 1
    UNION ALL
    SELECT valor2 FROM teste3 WHERE id = 2
  ) x;
  • 1

    haha, it worked, I don’t even think about using Union, thanks for the help!

  • Beware of using UNION here, if the columns VALUE and VALOR2 have the same value, the result will not be correct.

  • @Brune Why ?

  • 1

    @ramaral because UNION does the same job in DISTINCT showing only once records with equal values

Browser other questions tagged

You are not signed in. Login or sign up in order to post.