How do I add values from different tables?

Asked

Viewed 51 times

0

I have two tables (Costs and Receipts) where I need to make one sum of the field containing values of each of them, after making a calculation (Balance) showing the balance of the Revenue - Costs = Balance.

Follow the information of the two tables:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • the fields I need to make a sum are: recipe value and cost_value. All float type

  • @Virgilionovic I actually created a chart just for that.

  • I created a table called saldoprocesso to do the joins, but I doubt if this is necessary? and if it works by doing this too.

1 answer

0

I think you don’t need this other table. Maybe a view can be useful, depends on your decision.

Try the SQL below:

SELECT
    CUSTAS_SOMA,
    RECEITAS_SOMA,
    (RECEITAS_SOMA-CUSTAS_SOMA) AS SALDO
FROM (
    SELECT
        (SELECT SUM(valor_custas) FROM custas ) AS CUSTAS_SOMA,
        (SELECT SUM(valor_receitas) FROM receitas) AS RECEITAS_SOMA
) AS SOMAS

In codeigniter, you can use:

$result=$this->db->query("
    SELECT
        CUSTAS_SOMA,
        RECEITAS_SOMA,
        (RECEITAS_SOMA-CUSTAS_SOMA) AS SALDO
    FROM (
        SELECT
            (SELECT SUM(valor_custas) FROM custas ) AS CUSTAS_SOMA,
            (SELECT SUM(valor_receitas) FROM receitas) AS RECEITAS_SOMA
    ) AS SOMAS
"));

$S=$result->first_row();

echo "Custos: ".$S->CUSTAS_SOMA."<br />";
echo "Receitas: ".$S->RECEITAS_SOMA."<br />";
echo "Saldo: ".$S->SALDO;
  • how this query would look in Codeigniter?

  • edited the answer

  • in the IC is not working this way

  • @Ramiro tested the query here and it worked. As for Codeigniter, try changing $S=$result->first_row(); for $S=$result->Row().

Browser other questions tagged

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