Skip to main content
2 de 5
adicionei conteúdo
WITH RECURSIVE Q (rowid, data, fornecedor, credito, debito, saldo) AS
(
    SELECT 1, C.data, C.fornecedor, HCRED.valor_pago as credito, HDEB.valor_pago as debito, COALESCE(HDEB.valor_pago, 0) + COALESCE(HCRED.valor_pago, 0) as saldo
    FROM      tb_compras C
    LEFT JOIN tb_compras_historico_pagamento HCRED
              ON C.id = HCRED.id_compra AND HCRED.valor_pago > 0
    LEFT JOIN tb_compras_historico_pagamento HDEB
              ON C.id = HDEB.id_compra AND HDEB.valor_pago < 0

    UNION

    SELECT Q.data, Q.fornecedor, Q.credito, Q.debito, COALESCE(Q.credito, 0) + COALESCE(Q.debito, 0) + Q.saldo
    FROM Q
    INNER JOIN tb_compras C ON Q.rowid = C.id + 1
)
SELECT *
FROM Q
ORDER BY 1, 2;