Sum of a column is not giving the expected value

-2

I have a dummy table with two columns and some data in it, depending on the image.

When I execute my following SQL statement, the result of the query is 22. The result should not only be 12? I could not understand why.

Could anyone explain?

SQL:

SELECT sum(a.coluna1)
  FROM dados AS A 
 WHERE EXISTS (SELECT TRUE 
                 FROM dados AS B
                 WHERE (a.coluna1/b.coluna2) >= 1);
    
asked by anonymous 24.05.2017 / 03:04

3 answers

1

This your SQL does not make much sense, I think what you wanted to do was this:

 SELECT sum(coluna1)
 FROM dados 
 WHERE ((coluna1/coluna2) >= 1)

See if it works that way.

What this SQL I told you to do, is to add the values when column1 / column2 is greater than or equal to 1.

    
24.05.2017 / 04:24
0

The problem is that in subquery you say that the current line of table A when divided by any line of table B the result is maior/igual to 1, you will add the value of column 1.

Using your same syntax, to solve this problem, simply specify that in subselect the line from which to get the column B should be the same line as the column A < strong>, see the example:

SELECT sum(a.coluna1)
  FROM dados AS A 
 WHERE EXISTS (SELECT TRUE 
                 FROM dados AS B
                 WHERE a.coluna1 = b.coluna1 and (a.coluna1/b.coluna2) >= 1);

However, this code does not make much sense ...

As your colleague Isaias has shown, it does not make much sense to give subselect with Exists to do this calculation, just do as he did.

    
24.05.2017 / 13:44
0

Analyzing your SQL:

SELECT sum(a.coluna1)
  FROM dados AS A 
 WHERE EXISTS (SELECT TRUE 
                 FROM dados AS B
                 WHERE (a.coluna1/b.coluna2) >= 1);

It returns 22 because you tell it to add the a.coluna1 column when the condition passed in the WHERE clause between "()" , it returned TRUE , so it added, if it returns FALSE it would not add anything.

I think that's what you wanted:

SELECT SUM(a.coluna1)
  FROM dados AS a
 WHERE id IN (SELECT id
                FROM dados AS b
               WHERE (a.coluna1 / b.coluna2) >= 1);

So your query will sum the data from the a.coluna1 column where id exists within the condition passed in the WHERE clause between "()" .

    
14.07.2017 / 19:59