I have 3 tables faturas
, parcelas
and pagamentos
. Now I need to mount an SQL to count the parcels that are not removed. I already tried SUM(CASE
but it did not work.
Structure of the faturas
table:
id_fa
tipo
data_emissao
valor_fatura
Structure of the parcelas
table:
id_pa
id_fatura
data_vcto
valor_parcela
Structure of the pagamentos
table:
id_pg
id_parcela
data_pgto
valor_bruto
valor_desconto
valor_juros
valor_multa
valor_pago
My query attempt:
SELECT
id_pa,
SUM(CASE WHEN lc_pagamentos.id_parcela=lc_parcelas.id_pa THEN lc_pagamentos.valor_bruto ELSE 0 END) AS vBruto
FROM lc_faturas, lc_parcelas, lc_pagamentos
WHERE lc_faturas.ID=lc_parcelas.ID
In this way it only counts the number of parcels, but I need to compare the valor_parcela
field of the parcelas
table with the sum of the valor_bruto
field of the pagamentos
table and return only the records that are different, that is, return the portion that is not removed.