• 0
Sign in to follow this  
Anderson Dos Santos Salgado

Consulta com soma entre 2 tabelas Mysql

Question

1 answer to this question

Recommended Posts

  • 0

Tente assim:

SELECT r1.ano_mes, r1.total_receitas, d1.total_despesas, (r1.total_receitas - d1.total_despesas) AS saldo
FROM (
   SELECT SUBSTRING(r.data, 1, 7) AS ano_mes, SUM(r.receitas) AS total_receitas
   FROM receitas r
   GROUP BY SUBSTRING(r.data, 1, 7)
)r1
LEFT JOIN (
   SELECT SUBSTRING(d.data, 1, 7) AS ano_mes, SUM(r.despesas) AS total_despesas
   FROM despesas d
   GROUP BY SUBSTRING(d.data, 1, 7)
)d1 ON d1.ano_mes = r1.ano_mes

Tenha cuidado para não executar esta select com um período grande ou com um número elevado de registros, pois, por não conter índices em ano_mes, sempre executará por TABLE SCAN.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this