I have this query that have this output (the correct):
15
44
Query:
SELECT T.numContribuinte,
T.numero,
SUM(C.valor - T.valorTotalChamadas) AS saldo
FROM telemovel T
JOIN CARREGAMENTO C ON C.numero = T.numero
GROUP BY T.numContribuinte, T.numero
HAVING saldo > 0
ORDER BY T.numero DESC
If I remove the word sum the output will be:
15
15
My question is
Why the absence of the sum produce this difference in the output?
The reason for the difference is that by design, MySQL allows columns in the SELECT to not be stated in the
GROUP BYor aggregate functions (MAX, MIN, COUNT, etc). The caveat to this functionality is the values returned are arbitrary — they can’t be guaranteed to be consistent every time.The support is in line with what’s dictated by ANSI, but few (SQLite only to my knowledge) support this behavior. Others require the column to either be mentioned in the
GROUP BYor enclosed in an aggregate function.