Subtraction of values in the same table and column

Asked

Viewed 91 times

0

I have a table in phpMyAdmin called flow, in this table is the flow of a box

Amostra da tabela

(The description would tell us what each record is for)

I need to have a way to achieve the net profit of each month in a 1-year period so that the first record is the oldest and the last the newest.

I tried to sum the profit grouping by month, do the same thing with expenses and subtract one column from the other and only filter the desired columns at the end with SELECT:

SELECT
    Valor,
    DataN
FROM
    (
    SELECT
        COALESCE((L.Valor - G.Valor),
        L.valor) AS Valor,
        MONTHNAME(L.Data) AS DataN,
        L.Data AS DATA
    FROM
        (
        SELECT
            `ID`,
            SUM(`Valor`) AS Valor,
            `Data` AS DATA
        FROM
            `fluxo`
        WHERE
            `Tipo` = 'Lucro'
        GROUP BY
            YEAR(`Data`),
            MONTH(`Data`)
        ORDER BY
            YEAR(`Data`),
            MONTH(`Data`)
        DESC
    ) AS L
LEFT JOIN(
    SELECT `ID`,
        SUM(`Valor`) AS Valor,
        `Data` AS DATA
    FROM
        `fluxo`
    WHERE
        `Tipo` = 'Gasto'
    GROUP BY
        YEAR(`Data`),
        MONTH(`Data`)
    ORDER BY
        YEAR(`Data`),
        MONTH(`Data`)
    DESC
) AS G
ON
    L.Data = G.Data
ORDER BY
    YEAR(L.`Data`)
DESC
    ,
    MONTH(L.`Data`)
DESC
LIMIT 12
) F
ORDER BY
    YEAR(F.`Data`) ASC,
    MONTH(F.`Data`) ASC

But something’s going wrong and I don’t know what it is.

1 answer

0

Follow an example of use

Select month(data) as mes, year(data) as ano, coalesce(flucro.total, 0) as lucro, coalesce(fgasto.total, 0) as gasto, (coalesce(flucro.total, 0) - coalesce(fgasto.total, 0)) as saldo from fluxo left join (Select Sum(valor) as total, month(data) as mes, year(data) as ano from fluxo as flucro where tipo = 'Lucro' group by 2, 3) as flucro on month(data) = flucro.mes and year(data) = flucro.ano left join (Select Sum(valor) as total, month(data) as mes, year(data) as ano from fluxo as fgasto where tipo = 'Gasto' group by 2, 3) as fgasto on month(data) = fgasto.mes and year(data) = fgasto.ano group by 1,2 order by 1,2

  • The following error appeared: #1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'flucro.total' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Browser other questions tagged

You are not signed in. Login or sign up in order to post.