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.