Solution to Visualize Monthly Growth:
Follow a query to get the columns and the growth rate monthly
(assuming that each line was a month).
For larger or total periods, 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 necessary.
Notice that it pays to do two darlings separate, to simplify, one with SET and one with SELECT.
The IF used to calculate growth does the following::
- if the previous value is non-zero, returns the growth rate in percentage.
- if the previous value is zero, returns
?
. You can replace the ?
by the value you find convenient for your application, such as 100, for example.
Without this IF
we would have trouble making a split by zero.
Values are being returned in percentage. To return the numeric index only, simply remove the *100
of the formula.
Click here for a functional example on SQL Fiddle
Based on your Pastebin PHP 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 functions mysql_
, because they are insecure and are obsolete. The example provided was only to be able to meet what was requested at the time. I recommend you study the functions mysqli_
and convert your code.
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero