2
I have this following query:
SELECT FORMAT(SUM(receitas_dia) - SUM(despesas_dia),2,'de_DE') AS saldo_efetivo
FROM
(SELECT SUM(r.valor_receita) AS receitas_dia,
(SELECT SUM(d.valor_despesa)
FROM despesas AS d
WHERE d.pago = 1 AND d.data_vencimento = r.data_vencimento
AND d.id_usuario = r.id_usuario) AS despesas_dia
FROM receitas AS r
WHERE r.recebido = 1 AND YEAR(r.data_vencimento) <= '2017'
AND MONTH(r.data_vencimento) <= '06'
AND r.id_usuario = 1
GROUP BY r.data_vencimento) AS receita_despesas
It works well if the value of the revenue is greater than that of the expense... But if the value of the revenue is lower, it does not return the negative value, and yes NULL
.
How do I so that even if the recipe is smaller, it subtracts and returns the negative real value. (Fields of type DECIMAL).
@EDIT: My final query:
SELECT
FORMAT(SUM(t.valor),2,'de_DE') AS saldo_efetivo
FROM (
SELECT
d.valor_despesa*-1 AS valor,
d.data_vencimento,
d.pago AS realizado,
d.id_usuario
FROM despesas AS d
UNION
SELECT
r.valor_receita,
r.data_vencimento,
r.recebido AS realizado,
r.id_usuario
FROM receitas AS r
) t WHERE YEAR(t.data_vencimento) <= 2017
AND MONTH(t.data_vencimento) <= 06
AND t.realizado = 1
AND t.id_usuario = 1
the
IFNULL
should be inside theSUM
otherwise it will always return 0 when some line isNULL
and that is not what is desired– Rovann Linhalis
This way you are only changing NULL to 0. I want you to return the negative value if the subtraction result is negative.
– Eduardo Henrique
And if there is no record it will return null. In reality if you analyze the objective of its table, there should be no null values
– Sorack
@Eduardohenrique tests now. I made a change
– Sorack
yeah, I don’t understand the need to make one table for expenses and another for revenues, if everything is movement and should be added after
– Rovann Linhalis
Thanks for the answer! Still returning 0 this way...
– Eduardo Henrique
@Rovannlinhalis There are several columns for both tables... In the expense table there are more columns than in the revenue table.
– Eduardo Henrique
@Eduardohenrique alright, it would be easier to ignore some unused columns in a table, than to keep adding two different tables. But then it’s a question of modeling, it’s not the case
– Rovann Linhalis