1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] Find first uncovered debt month in Oracle Sql

Discussão em 'Outras Linguagens' iniciado por Stack, Outubro 1, 2024 às 07:12.

  1. Stack

    Stack Membro Participativo

    I want to find first month in which the debt is not fully covered. I will try to explain:

    A subscriber took 10$ debt in July and paid 5$, In August took 5$ and paid 5$, In September took 5$ and paid 2$, In October took 2$ and didn't paid. If the debt is not paid in the current month, then the previous debts should be paid with the next month's payments. So, July's debt fully covered in august and August's debt not fully covered. So, August must be "first uncover month". How can I write script in oracle SQL to find "first uncover month"?

    this is table:

    CREATE TABLE debt_payments (
    month VARCHAR2(10),
    debt_taken NUMBER,
    payment NUMBER
    );

    INSERT INTO debt_payments (month, debt_taken, payment) VALUES ('July', 10, 5);
    INSERT INTO debt_payments (month, debt_taken, payment) VALUES ('August', 5, 5);
    INSERT INTO debt_payments (month, debt_taken, payment) VALUES ('September', 5, 2);
    INSERT INTO debt_payments (month, debt_taken, payment) VALUES ('October', 2, 0);



    I wrote this but didn't work real base and only find first month when remaining_debt > 0.

    WITH debt_summary AS (
    SELECT
    month,
    SUM(debt_taken) OVER (ORDER BY month) AS total_debt,
    SUM(payment) OVER (ORDER BY month) AS total_payment
    FROM
    debt_payments
    ),
    remaining_debt AS (
    SELECT
    month,
    total_debt - total_payment AS remaining_debt
    FROM
    debt_summary
    )
    SELECT
    month
    FROM
    remaining_debt
    WHERE
    remaining_debt > 0
    ORDER BY
    month
    FETCH FIRST ROW ONLY; -- Get the first month where debt is uncovered

    Continue reading...

Compartilhe esta Página