我有一个名为“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
我试图找到两个月之间相同项目名称的“distmoney”之间的区别仅限于一个特定项目(通过使用WHERE id = $ id)
示例:
ID 1,itemname chicken。第12个月的distmoney是20,而第11个月的distmoney是21.我希望能够计算id = 1,itemname = chicken的1的差异。它应该只显示鸡肉的差异,而不是任何其他项目名称(如猪肉)。
现在我有PHP代码来计算两个数字之间的差异,但我很难搞清楚如何抓住上个月的数据。
能够找到上个月的特定项目名称并将其插入名为“oldmoney”的新列中也可以,但我不知道如何执行此操作。
示例:对于id 3,itemname chicken。当前的distmoney是20,上个月(在id = 1中找到)是20.让我们取20并将其插入id 3下的新列。
<?php
foreach($rows as $row):
$number1 = htmlentities($row['distmoney'])
endforeach;
$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 "%";
}
&GT;
答案 0 :(得分:1)
当您查询项目时,ORDER BY 项目名称 首先。
然后,做一些像
这样的事情//Create a variable to hold the "previous month" values
$previousItemName = '';
$previousDistMoney = '';
//Check each record from your query
foreach($rows as $row) {
//If not first time around && same item name as previous
if($previousItemName != '' && $previousItemName == $row['itemname']) {
//subtraction calculation here
//$difference = $row['distmoney'] - $previousDistMoney; ??
//echo $difference; ??
}
//Assign the "previous month" value
$previousItemName = $row['itemname'];
$previousDistMoney = $row['distmoney'];
}
虽然这两种方式都有点脏,但你也可以做一个循环:for($ i = 0; $ i&lt; count($ results); $ i ++){}
然后检查$ results [$ i-1] ['distmoney'];
的值编辑。
如果您知道查询字符串中的ID,只需将其放入查询中......这样只返回2个'鸡'记录:
select itemname, distmoney from items where itemname in (
select itemname from items where id = 3
)