From what you say, you need to add the rows of the two tables by date. For this, you should first group each table by date independently and then join them by a join
. If you do the join
directly, you will duplicate rows in one or both tables, provided that you have more than one row for the same date in one of the two tables or both.
What I was saying, would be something like this:
SELECT I.FECHA,
I.INVERSION_VALOR,
G.GASTO_VALOR
FROM (SELECT FECHA,
SUM(VALOR) AS INVERSION_VALOR
FROM INVERSION
GROUP BY FECHA
) I
LEFT JOIN (SELECT FECHA,
SUM(VALOR) AS GASTO_VALOR
FROM GASTOS
GROUP BY(FECHA)
) G
ON G.FECHA = I.FECHA
This has an eventual problem, just as the query will bring you all rows of inversion
and only those that match gastos
. This would be easily solved if mysql had a FULL OUTER JOIN
, unfortunately it is not so you have to emulate it in this way:
SELECT I.FECHA,
I.INVERSION_VALOR,
G.GASTO_VALOR
FROM (SELECT FECHA,
SUM(VALOR) AS INVERSION_VALOR
FROM INVERSION
GROUP BY FECHA
) I
LEFT JOIN (SELECT FECHA,
SUM(VALOR) AS GASTO_VALOR
FROM GASTOS
GROUP BY(FECHA)
) G
ON G.FECHA = I.FECHA
UNION
SELECT I.FECHA,
I.INVERSION_VALOR,
G.GASTO_VALOR
FROM (SELECT FECHA,
SUM(VALOR) AS INVERSION_VALOR
FROM INVERSION
GROUP BY FECHA
) I
RIGHT JOIN (SELECT FECHA,
SUM(VALOR) AS GASTO_VALOR
FROM GASTOS
GROUP BY(FECHA)
) G
ON G.FECHA = I.FECHA
WHERE I.FECHA IS NULL
If in any of the two tables you do not have rows, keep in mind that obviously the columns of amounts will return null
, if you prefer to show the value 0, you should use a IFNULL(G.GASTO_VALOR, 0)
or IFNULL(G.INVERSION_VALOR, 0)