1

我有一个名为“项目”的表

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,物品名称 chicken。第 12 个月的 distmoney 是 20,而第 11 个月的 distmoney 是 21。我希望能够计算 id=1、itemname=chicken 的差值 1

现在我有 php 代码来计算两个数字之间的差异,但我很难弄清楚如何抓住上个月的 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 "%";
} 

?>

4

2 回答 2

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];
    }
}
于 2013-01-15T01:20:43.093 回答
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

查询的结果是:

| ITEMNAME | DEC2012 | NOV2012 |
--------------------------------
|  chicken |      20 |      21 |
|     pork |      15 |      15 |
于 2013-01-15T01:25:01.667 回答