I have a table called “items”
id month year **itemname** distmoney
1 12 2012 chicken 20
2 12 2012 pork 15
3 11 2012 chicken 21
4 11 2012 pork 15
I am trying to find the difference between the “distmoney” for the same itemname between two months.
Example:
ID 1, itemname chicken. month 12 distmoney is 20, while month 11 distmoney is 21. I want to be able to calculate the difference of 1 for id=1, itemname=chicken
Right now I have the php code to calculate the difference between two numbers, but I am having a tough time figuring out how to grab the previous month distmoney.
<?php foreach($rows as $row): ?>
<?php $number1 = htmlentities($row['distmoney']) ?>
<?php endforeach; ?>
<?php
$number1 = $row['distmoney'];
$number2 = ????????; // THIS NEEDS TO BE THE PREVIOUS MONTH DISTMONEY VALUE
if ($number1 <= $number2) {
$difference = "(Price Lowered) Price difference of $";
$result = $number2 - $number1;
$percent = round(100.0*($number2-$number1)/$number1);
echo $difference; echo $result; echo $percent; echo "%";
} elseif ($number1 > $number2) {
$result = $number1 - $number2;
$percent = round(100.0*($number2/$number1-1));
$addition = "(Price Higher) Price difference of $";
echo $addition; echo $result; echo $percent; echo "%";
}
?>
If you want to perform this in SQL, then you can transform the data in columns to then get the difference:
See SQL Fiddle with Demo
The result of the query is: