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 smaller, it does not return the negative value, but NULL
.
How do I make even though the recipe is smaller, it subtracts and returns the negative real value. (DECIMAL type fields).
@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