Calculation of percentage of growth

2

I have three columns that would be month , revenue and expenses . For example:

Mês       | Receita | Despesas 
Janeiro   | 2500    | 1000 
Fevereiro | 1000    | 500 

I would like to demonstrate the percentage growth using PHP and MySQL.

The file .sql is as:

CREATE TABLE 'financas'   
  'codusuario' int (11)NOT NULL AUTO_INCREMENT,
  'mes' varchar(100) NOT NULL,    
  'receitas' varchar(100) NOT NULL,    
  'despesas' text(100) NOT NULL,    
  PRIMARY KEY ('codusuario')   
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf
    
asked by anonymous 04.04.2014 / 00:43

3 answers

3

Solution to visualize monthly growth:

Following is a query for the columns and the monthly growth rate (assuming each row was a month). For larger periods, or total, simply adapt the solution to use SUM and GROUP BY or accumulate data in more @ variables .

SET @anterior=0;

SELECT
      id,
      receitas,
      despesas,
      @subtotal := (receitas-despesas) AS subtotal,
      IF( @anterior !=0, (@subtotal/@anterior-1)*100, '?' ) AS crescimento,
      @anterior := @subtotal
   FROM rendimentos;

Line breaks are not required.

Note that it pays to make two separate queries , for simplicity, one with SET and one with SELECT.

The IF used to calculate growth does the following:

  • If the previous value is non-zero, it returns the growth rate in percentage.
  • If the previous value is zero, it returns ? . You can replace ? with the value you find convenient for your application, such as 100, for example.
    Without this IF we would have problem doing a division by zero.

Values are being returned in percentage. To return the numeric index only, simply remove the *100 from the formula.

  

Click here to see a working example in SQL Fiddle

Based on your PHP pastebin code, to show the result:

$query1 = "SET @anterior=0;";
$query2 = "SELECT id, receitas, despesas, @subtotal := (receitas-despesas) AS subtotal, IF( @anterior !=0, (@subtotal/@anterior-1)*100, '?' ) AS crescimento, @anterior := @subtotal FROM rendimentos;";

$conn = mysql_connect($host, $user, $pass) or die("Erro na conexão com o banco de dados");
$db = mysql_select_db($d_b, $conn) or die("Erro na seleção do banco de dados");

$result1 = mysql_query(query1);
$result2 = mysql_query(query2);
echo "<table>";
while ($resultRow = mysql_fetch_assoc($result2)) {
   echo '<tr><td>';
   echo htmlentities($resultRow['id']);
   echo '</td><td>';
   echo htmlentities($resultRow['receitas']);
   echo '</td><td>';
   echo htmlentities($resultRow['despesas']);
   echo '</td><td>';
   echo htmlentities($resultRow['subtotal']);
   echo '</td><td>';
   echo htmlentities($resultRow['crescimento']);
   echo '</td></tr>';
}
echo "</table>";
  

IMPORTANT: Avoid using mysql_ functions because they are insecure and obsolete. The example provided was only to meet what was requested at the time. I recommend that you study the functions mysqli_ and convert your code.

    
04.04.2014 / 06:00
0

If I understood the question, the formula for calculating this is:

  

x = past revenue - current revenue / past revenue

     

recipe = x * 100

In the link below, there are more complex examples.

link

    
04.04.2014 / 04:38
0

SQL Fiddle Link.

<?php
// Proposta utilizando PDO e cálculo do rendimento no PHP

function obterConexaoComOBancoDeDados ($bancoDeDados, $host, $usuario, $senha) {
    $dsn = "mysql:dbname=$bancoDeDados;host=$host";

    try {
        return new PDO($dsn, $usuario, $senha);
    } catch (PDOException $excecao) {
        echo "Falha ao tentar obter uma conexão com o Banco de Dados: {$excecao->getMessage()}";
    }
}

$dbh = obterConexaoComOBancoDeDados("hgsandbox", "localhost", "root", "");

$sql = '
    SELECT
        mes,
        (receita - despesa) AS liquido
    FROM
        Financas
    /* Seria necessário um WHERE?*/
    WHERE
        Usuario_id = :usuarioId
    ORDER BY
        mes
';

$usuarioId = 1; // Id de um usuário.

$sth = $dbh->prepare($sql);
$sth->bindParam(':usuarioId', $usuarioId);
$sth->execute();

$linhas = $sth->fetchAll(PDO::FETCH_ASSOC);

foreach ($linhas as $indice => $linha) {
    if ($indice > 0) {
        $mesAtual = (int) $linha["mes"];
        $valorLiquidoAtual = (float) $linha["liquido"];

        $porcentagemAlteracao = (($valorLiquidoAtual/$valorLiquidoAnterior) - 1) * 100;

        echo "A porcentagem de alteração (crescimento/redução) do mês $mesAnterior para o $mesAtual é de {$porcentagemAlteracao}%.";
    }

   $mesAnterior = (int) $linha["mes"];
   $valorLiquidoAnterior = (float) $linha["liquido"];
}
    
04.04.2014 / 03:06