Add several selects

Asked

Viewed 55 times

0

How do I add the result of several selects, for example, I have 2 selects that each of them brings a value field, ie with the sum of something...

Select 1:

 SELECT SUM(ms.valor) as valor
 FROM risco1.margem_solicitada ms
 WHERE ms.codigo = 5410477
 AND ms.data= '26/05/2020'

Select 2:

 SELECT SUM(mbmf.valor - mbmf.valor_sacado) as valor
 FROM risco1.margem_solicitada2 mbmf
 WHERE mbmf.codigo = 5410477
 AND mbmf.data= '26/05/2020'

How are we the result of these 2 selects ? I have seen that just putting a '+' between them does not work...

2 answers

2


Do a subquery with the 2 selects (you can use union to join them), and then sum from that sum:

WITH totais AS(
SELECT SUM(ms.valor) as valor
 FROM risco1.margem_solicitada ms
 WHERE ms.codigo = 5410477
 AND ms.data= '26/05/2020'

UNION

SELECT SUM(mbmf.valor - mbmf.valor_sacado) as valor
 FROM risco1.margem_solicitada2 mbmf
 WHERE mbmf.codigo = 5410477
 AND mbmf.data= '26/05/2020'
)
select sum(valor) as totalfinal from totais

To manipulate the Queries, I used the WITH, that names the result for "totals", as if it were a table

  • Thanks, it worked out

0

Whenever you use a Union, make sure the columns have the same name. After using Union, you can create a view. And in another you group and account. Since I don’t have much experience I always use this resource.

Browser other questions tagged

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