Subtract sums of fields in two distinct tables

5

I need to add the value of a column in SQL, so it looks like this:

SELECT SUM(qtdsaco) FROM armazem

This code works. Now I need to add the value of the other table, it looks like this:

SELECT SUM(qtdsaco) FROM armazem2

So I had to take the result of the two and subtract. How do I?

    
asked by anonymous 24.08.2016 / 21:37

5 answers

3

You will have to see which table comes first and do this by throwing the value into a total :

SELECT (SUM(qtdsaco) - (SELECT SUM(qtdsaco) FROM armazem2)) total FROM armazem
    
24.08.2016 / 21:44
3

The SELECT serves to select information in any way. It does not even need to be from the database. It can select data if SQL subexpression, including other% s of% s. Then you can do each of them as subexpression and the subtraction of the two in SELECT principal.

SELECT (SELECT SUM(qtdsaco) FROM armazem) - (SELECT SUM(qtdsaco) FROM armazem2)

See running SQLFiddle .

Obviously you can get the same result with variations of SQL expression. I find this more appropriate because it is simple and clearly demonstrates intent. If I had other requirements I would opt for another way. I followed what the question asked ipsis litteris .

    
24.08.2016 / 21:42
2

Based on in this other answer of mine , I would do so:

SELECT a.c - b.d AS qtdsaco
FROM (SELECT SUM(qtdsaco) AS c FROM armazem) a,
     (SELECT SUM(qtdsaco) AS d FROM armazem2) b
    
24.08.2016 / 21:50
2

Make use of subselects :

select (SELECT SUM(qtdsaco) FROM armazem) - (SELECT SUM(qtdsaco) FROM armazem2)
    
24.08.2016 / 23:51
0

You can do a JOIN as follows.

declare @armazem table(qtdsaco int)
declare @armazem2 table( qtdsaco int)
insert into @armazem values(112),(3),(432),(22),(1),(5),(4),(3),(2)
insert into @armazem2 values(1),(2),(3),(4),(6),(5),(4),(3),(2)

select SUM(a1.qtdsaco) - SUM(a2.qtdsaco) total
from @armazem a1
join  @armazem2 a2 on 1 = 1
  

Obs; as the database was not specified, this was done in sql   server.

    
24.08.2016 / 22:03