itemname相同的两个数值之间的差异

时间:2013-01-15 01:10:02

标签: php mysql

我有一个名为“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”之间的区别。

示例:

ID 1,itemname chicken。第12个月distmoney是20,而第11个月是21个。我希望能够计算id = 1,itemname = chicken

的差异1

现在我有PHP代码来计算两个数字之间的差异,但我很难搞清楚如何抓住上个月的数据。

<?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 "%";
} 

&GT;

2 个答案:

答案 0 :(得分:1)

您可以预先处理数据,使其按项目名称分组,并存储该项目的distmoney值数组。假设数据已按日期正确排序。

$diff = array();
foreach($rows as $row)
{
   if(!isset($diff[$row['itemname']])
   {
      $diff[$row['itemname']] = array();
   }
   $diff[$row['itemname']][] = $row['distmoney'];
}

foreach($diff as $itemname=>$months)
{
    if(count($months) == 2)
    {
        echo $itemname.' difference: '.$months[0]-$months[1];
    }
}

答案 1 :(得分:1)

如果要在SQL中执行此操作,则可以在列中转换数据,然后获得差异:

select 
  itemname,
  max(case when month = 12 and year = 2012 then distmoney else 0 end) Dec2012,
  max(case when month = 11 and year = 2012 then distmoney else 0 end) Nov2012
from yourtable
group by itemname

请参阅SQL Fiddle with Demo

查询结果为:

| ITEMNAME | DEC2012 | NOV2012 |
--------------------------------
|  chicken |      20 |      21 |
|     pork |      15 |      15 |