I want to do a subtraction of the total value of a column of a table, with the total value of a column of another table.
Query:
SELECT (
SUM(r.valor_receita) -
(
SELECT SUM(d.valor_despesa)
FROM
despesas AS d
WHERE
YEAR(d.data_vencimento) = YEAR(r.data_vencimento)
AND MONTH(d.data_vencimento) <= MONTH(r.data_vencimento)
AND d.id_usuario = r.id_usuario)
) AS saldo_previsto
FROM
receitas AS r
WHERE
YEAR(r.data_vencimento) = '2017'
AND MONTH(r.data_vencimento) <= '06'
AND r.id_usuario = 1
The where
clause of the 'expenditure' table should be the same as the where
of revenue clause.
EDIT: Tables: link
So it should be the query:
SELECT (
SUM(r.valor_receita) -
(
SELECT SUM(d.valor_despesa)
FROM
despesas AS d
WHERE
YEAR(d.data_vencimento) = '2017'
AND MONTH(d.data_vencimento) <= '06'
AND d.id_usuario = 1)
) AS saldo_previsto
FROM
receitas AS r
WHERE
YEAR(r.data_vencimento) = '2017'
AND MONTH(r.data_vencimento) <= '06'
AND r.id_usuario = 1
The only difference is that I'm passing the year, month, and user id parameters again. Is there any way to make this work without having to pass the values twice?